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:com.conversantmedia.mapreduce.tool.RunJob.java

/**
 * Outputs the driver's list//from  ww w.  j  a  v a  2  s .co  m
 * 
 * @param driversMap   map of driver metadata to output to console
 */
protected static void outputDriversTable(Map<String, DriverMeta> driversMap) {

    String[] colNames = new String[] { "Name", "Description", "Ver", "Class" };
    String[] aligns = new String[] { "-", "-", "-", "-" };
    int maxDescriptionWidth = 48;
    int widths[] = new int[colNames.length];
    for (int i = 0; i < colNames.length; i++) {
        widths[i] = colNames[i].length();
    }
    int padding = 2;
    for (Entry<String, DriverMeta> e : driversMap.entrySet()) {
        if (!e.getValue().hidden) {
            int i = 0;
            widths[i] = Math.max(e.getKey().length(), widths[i]);
            widths[i + 1] = Math.min(Math.max(e.getValue().description.length(), widths[i + 1]),
                    maxDescriptionWidth);
            widths[i + 2] = Math.max(e.getValue().version.length(), widths[i + 2]);
            widths[i + 3] = Math.max(e.getValue().driverClass.getName().length(), widths[i + 3]);
        }
    }

    // sum widths
    int width = padding * widths.length - 1;
    for (int w : widths) {
        width += w;
    }

    String sep = StringUtils.repeat("=", width);
    System.out.println(sep);
    System.out.println(StringUtils.center("A V A I L A B L E    D R I V E R S", width));
    System.out.println(sep);
    String[] underscores = new String[colNames.length];
    StringBuilder headersFormatSb = new StringBuilder();
    StringBuilder valuesFormatSb = new StringBuilder();
    for (int i = 0; i < widths.length; i++) {
        headersFormatSb.append("%-").append(widths[i] + padding).append("s");
        valuesFormatSb.append("%").append(aligns[i]).append(widths[i] + padding).append("s");
        underscores[i] = StringUtils.repeat("-", widths[i]);
    }
    String format = headersFormatSb.toString();
    System.out.format(format, (Object[]) colNames);
    System.out.println();
    System.out.format(format, (Object[]) underscores);
    System.out.println();

    format = valuesFormatSb.toString();
    List<String> descriptionLines = new ArrayList<>();
    for (Entry<String, DriverMeta> e : driversMap.entrySet()) {
        if (!e.getValue().hidden) {
            descriptionLines.clear();
            String description = e.getValue().description;
            if (description.length() > maxDescriptionWidth) {
                splitLine(descriptionLines, description, maxDescriptionWidth);
                description = descriptionLines.remove(0);
            }
            System.out.format(format, e.getKey(), description,
                    StringUtils.center(e.getValue().version, widths[2]), e.getValue().driverClass.getName());
            System.out.println();
            while (!descriptionLines.isEmpty()) {
                System.out.format(format, "", descriptionLines.remove(0), "", "");
                System.out.println();
            }
        }
    }
}

From source file:com.stratio.crossdata.sh.Shell.java

/**
 * Shell loop that receives user commands until a {@code exit} or {@code quit} command is
 * introduced./*from   w  w  w .  j a v a2 s .  c o  m*/
 */
public void loop() {
    try {
        String cmd = "";
        StringBuilder sb = new StringBuilder(cmd);
        String toExecute;
        String currentPrompt = "";
        while (!cmd.trim().toLowerCase().startsWith("exit") && !cmd.trim().toLowerCase().startsWith("quit")) {
            cmd = console.readLine();
            sb.append(cmd).append(" ");
            toExecute = sb.toString().replaceAll("\\s+", " ").trim();
            if (toExecute.startsWith("//") || toExecute.startsWith("#")) {
                LOG.debug("Comment: " + toExecute);
                sb = new StringBuilder();
            } else if (toExecute.startsWith("/*")) {
                LOG.debug("Multiline comment START");
                if (console.getPrompt().startsWith(DEFAULT_PROMPT)) {
                    currentPrompt = console.getPrompt();
                    String tempPrompt = StringUtils.repeat(" ", DEFAULT_PROMPT.length() - 1)
                            + DEFAULT_TEMP_PROMPT + " ";
                    console.setPrompt(tempPrompt);
                }
                if (toExecute.endsWith("*/")) {
                    LOG.debug("Multiline comment END");
                    sb = new StringBuilder();
                    if (!console.getPrompt().startsWith(DEFAULT_PROMPT)) {
                        console.setPrompt(currentPrompt);
                    }
                }
            } else if (toExecute.endsWith(";")) {
                if (toExecute.toLowerCase().startsWith("help")) {
                    showHelp(sb.toString());
                } else {
                    try {
                        Result result = crossdataDriver.executeAsyncRawQuery(toExecute, resultHandler);
                        LOG.info(ConsoleUtils.stringResult(result));
                        updatePrompt(result);
                    } catch (Exception ex) {
                        LOG.error("Execution failed: " + ex.getMessage());
                    }
                }
                sb = new StringBuilder();
                if (!console.getPrompt().startsWith(DEFAULT_PROMPT)) {
                    console.setPrompt(currentPrompt);
                }
                println("");
            } else if (toExecute.toLowerCase().startsWith("help")) {
                showHelp(sb.toString());
                sb = new StringBuilder();
                println("");
            } else if (toExecute.toLowerCase().startsWith("script")) {
                String[] params = toExecute.split(" ");
                if (params.length == 2) {
                    executeScript(params[1]);
                } else {
                    showHelp(sb.toString());
                }
                sb = new StringBuilder();
                println("");
            } else if (!toExecute.isEmpty()) {
                // Multiline code
                if (console.getPrompt().startsWith(DEFAULT_PROMPT)) {
                    currentPrompt = console.getPrompt();
                    String tempPrompt = StringUtils.repeat(" ", DEFAULT_PROMPT.length() - 1)
                            + DEFAULT_TEMP_PROMPT + " ";
                    console.setPrompt(tempPrompt);
                }
            }
        }
    } catch (IOException ex) {
        LOG.error("Cannot read from console.", ex);
    } catch (Exception e) {
        LOG.error("Execution failed:", e);
    }
}

From source file:io.anserini.doc.DataModel.java

public String generateEffectiveness(String collection) {
    Map<String, Object> config = this.collections.get(collection);
    StringBuilder builder = new StringBuilder();
    ObjectMapper oMapper = new ObjectMapper();
    List models = oMapper.convertValue((List) safeGet(config, "models"), List.class);
    List topics = oMapper.convertValue((List) safeGet(config, "topics"), List.class);
    List evals = oMapper.convertValue((List) safeGet(config, "evals"), List.class);
    for (Object evalObj : evals) {
        Eval eval = oMapper.convertValue(evalObj, Eval.class);
        builder.append(String.format("%1$-40s|", eval.getMetric().toUpperCase()));
        for (Object modelObj : models) {
            Model model = oMapper.convertValue(modelObj, Model.class);
            builder.append(String.format(" %1$-10s|", model.getName().toUpperCase()));
        }//w ww.j a va 2  s .c o m
        builder.append("\n");
        builder.append(":").append(StringUtils.repeat("-", 39)).append("|");
        for (Object modelObj : models) {
            builder.append(StringUtils.repeat("-", 11)).append("|");
        }
        builder.append("\n");
        for (int i = 0; i < topics.size(); i++) {
            Topic topic = oMapper.convertValue(topics.get(i), Topic.class);
            builder.append(String.format("%1$-40s|", topic.getName().toUpperCase()));
            for (Object modelObj : models) {
                Model model = oMapper.convertValue(modelObj, Model.class);
                builder.append(String.format(" %-10.4f|", model.getResults().get(eval.getMetric()).get(i)));
            }
            builder.append("\n");
        }
        builder.append("\n\n");
    }
    builder.delete(builder.lastIndexOf("\n"), builder.length());

    return builder.toString();
}

From source file:com.zilbo.flamingSailor.TE.model.Component.java

public void dumpChildren(PrintStream out, int level) {

    StringBuilder sb = new StringBuilder();

    sb.append(StringUtils.repeat("..", level));
    sb.append(getClass().getSimpleName());
    if (sb.length() < 20) {
        sb.append(StringUtils.repeat(' ', 20 - sb.length()));
    }//from  w ww .  j av a  2  s  .co  m
    sb.append('\t');
    sb.append(getRectangleDebug()).append(" \t");
    //  sb.append(getText().replace("\n", "\n" + StringUtils.repeat(' ', 43)));
    String text;
    if (sb.length() > 256) {
        text = sb.substring(0, 256 - 4) + " ...";
    } else {
        text = sb.toString();
    }
    out.println(text);
    for (Component component : getChildren()) {
        component.dumpChildren(out, level + 1);
    }
}

From source file:de.uniwue.info6.webapp.admin.AdminEditScenario.java

/**
 *
 *
 *//* w w w .j  a  v a 2s. co m*/
@PostConstruct
public void init() {
    userHasRights = false;
    ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
    scenarioDao = new ScenarioDao();
    exerciseDao = new ExerciseDao();
    userRightsDao = new UserRightDao();
    exerciseGroupDao = new ExerciseGroupDao();
    solutionQueryDao = new SolutionQueryDao();
    Map<String, String> requestParams = ec.getRequestParameterMap();
    ac = SessionObject.pullFromSession();
    user = ac.getUser();
    connectionPool = ConnectionManager.instance();
    uploader = new FileTransfer();
    rights = new UserRights().initialize();
    debugMode = Cfg.inst().getProp(MAIN_CONFIG, DEBUG_MODE);

    if (user != null) {
        this.isAdmin = rights.isAdmin(user);
        this.isLecturer = rights.isLecturer(user);
    }

    if (!requestParams.isEmpty()) {
        try {
            // exercise get-parameter found
            if (requestParams.containsKey(SCENARIO_PARAM)) {
                String param = requestParams.get(SCENARIO_PARAM);
                final int id = Integer.parseInt(param);
                scenario = scenarioDao.getById(id);

                if (scenario == null) {
                    if (rights.isAdmin(user) || rights.isLecturer(user)) {
                        userHasRights = true;
                    }
                } else {
                    if (rights.hasEditingRight(user, scenario)) {
                        userHasRights = true;
                        lastModified = scenario.getLastModified();
                        scenarioName = scenario.getName();
                        description = scenario.getDescription();
                        scriptPath = scenario.getCreateScriptPath();
                        imagePath = scenario.getImagePath();
                        dbHost = scenario.getDbHost();
                        dbUser = scenario.getDbUser();

                        // ------------------------------------------------ //
                        final boolean showCaseMode = Cfg.inst().getProp(MAIN_CONFIG, SHOWCASE_MODE);
                        if (showCaseMode) {
                            // don't show the actual password
                            dbPass = StringTools.generatePassword(64, 32);
                        } else {
                            dbPass = scenario.getDbPass();
                        }
                        // ------------------------------------------------ //

                        dbPort = scenario.getDbPort();
                        dbName = scenario.getDbName();
                        startDate = scenario.getStartTime();
                        endDate = scenario.getEndTime();

                        if (scenario.getScenario() != null) {
                            originalScenarioId = scenario.getScenario().getId();
                        }

                        if (scriptPath != null && !scriptPath.isEmpty()) {
                            File absPath = getSourceFile(scriptPath, false);
                            scriptFile = absPath;
                            scriptStream = uploader.getFileToDownload(absPath);
                        }

                        if (imagePath != null) {
                            File absPath = getSourceFile(imagePath, false);
                            imageFile = absPath;
                            imageStream = uploader.getFileToDownload(absPath);
                        }
                    }

                }
            }
        } catch (NumberFormatException e) {
            if (rights.isAdmin(user) || rights.isLecturer(user)) {
                userHasRights = true;
            }
        } catch (Exception e) {
            LOGGER.error("ERROR GETTING SCENARIO FIELDS FROM DATABASE", e);
        }
    }

    if (debugMode) {
        final Random random = new Random();
        scenarioName = "debug-name-" + random.nextInt(1000);
        description = StringUtils.repeat("debug-description ", 50);
    }

    updateRightScripts();
}

From source file:com.adobe.acs.commons.hc.impl.HealthCheckStatusEmailer.java

/**
 * Gererates the plain-text email sections for sets of Health Check Execution Results.
 *
 * @param title The section title//from  ww  w.j  a  va 2  s .c  o  m
 * @param results the  Health Check Execution Results to render as plain text
 * @return the String for this section to be embedded in the e-mail
 */
protected String resultToPlainText(final String title, final List<HealthCheckExecutionResult> results) {
    final StringBuilder sb = new StringBuilder();

    sb.append(title);
    sb.append(System.lineSeparator());

    if (results.size() == 0) {
        sb.append("No " + StringUtils.lowerCase(title) + " could be found!");
        sb.append(System.lineSeparator());
    } else {
        sb.append(StringUtils.repeat("-", NUM_DASHES));
        sb.append(System.lineSeparator());

        for (final HealthCheckExecutionResult result : results) {
            sb.append(StringUtils.rightPad("[ " + result.getHealthCheckResult().getStatus().name() + " ]",
                    HEALTH_CHECK_STATUS_PADDING));
            sb.append("  ");
            sb.append(result.getHealthCheckMetadata().getTitle());
            sb.append(System.lineSeparator());
        }
    }

    return sb.toString();
}

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

/**
 *
 * This makes sure to pad front and back of the string, if pad is True.
 *
 * @param n size of ngram/* w w  w .  j a va2  s.com*/
 * @param examples list of examples
 * @param pad whether or not we should use padding.
 * @return
 */
public static HashMap<String, Integer> GetNgramCounts(int n, Iterable<String> examples, boolean pad) {
    HashMap<String, Integer> result = new HashMap<>();
    for (String example : examples) {
        String padstring = StringUtils.repeat("_", n - 1);
        String paddedExample = (pad ? padstring + example + padstring : example);

        for (int i = 0; i <= paddedExample.length() - n; i++) {
            //System.out.println(i + ": " + n);
            Dictionaries.IncrementOrSet(result, paddedExample.substring(i, i + n), 1, 1);
        }
    }

    return result;
}

From source file:de.bund.bva.pliscommon.ueberwachung.common.jmx.ServiceStatistikMBean.java

/**
 * Durchsucht eine Klasse nach Fehlerobjekten, die nicht null sind, oder Fehlercollections, die nicht leer
 * sind. Fehlerobjekten sind mit {link FachlicherFehler} annotiert.
 *
 * Durchsucht Oberklassen & untergeordnete Objektstrukturen ebenfalls rekursiv.
 *
 * @param result//from   www . jav a2s.  c  o m
 *            Das Objekt
 * @param clazz
 *            Die Klasse des Objekts durchsucht werden soll (optional). Kann leergelassen werden beim
 *            Start, kann aber genutzt werden um auf Oberklassen eines Objekts zu prfen.
 * @param tiefe
 *            tiefe Gibt die aktuelle Tiefe des Aufrufs an. Muss erhht werden wenn man die
 *            Klassenstruktur nach unten durchluft.
 * @return <code>true</code> wenn Fehler gefunden, ansonsten <code>false</code>
 */
boolean pruefeObjektAufFehler(final Object result, Class<?> clazz, int tiefe) {
    boolean fehlerGefunden = false;
    Class<?> clazzToScan = clazz;
    // Wenn keine Klasse bergeben, selber ermitteln
    if (clazzToScan == null) {
        clazzToScan = result.getClass();
    }

    // Wenn max. Tiefe erreicht, nicht weiter prfen
    if (tiefe > MAXTIEFE) {
        LOGISY.trace("Max. Tiefe erreicht, prfe nicht weiter auf fachliche Fehler");
        return false;
    }

    Field[] fields = clazzToScan.getDeclaredFields();

    LOGISY.trace("{} Analysiere Objekt {} (Klasse {}) {} Felder gefunden.", StringUtils.repeat("-", tiefe),
            result.toString(), clazzToScan.getSimpleName(), fields.length);

    for (Field field : fields) {
        if (!ClassUtils.isPrimitiveOrWrapper(field.getType()) && !field.getType().isEnum()) {
            LOGISY.trace("{} {}.{}, Type {}", StringUtils.repeat("-", tiefe), clazzToScan.getSimpleName(),
                    field.getName(), field.getType().getSimpleName());
            field.setAccessible(true);
            try {
                // Prfe einzelne Klassenfelder (non-Collection) auf annotierten Typ und Vorhandensein
                if (!Collection.class.isAssignableFrom(field.getType())) {
                    if (field.get(result) != null) {
                        Object fieldObject = field.get(result);
                        if (fieldObject.getClass().isAnnotationPresent(FachlicherFehler.class)) {
                            // Fachliches Fehlerobjekt gefunden
                            return true;
                        }

                        // Wenn kein String, dann prfe rekursiv Objektstruktur
                        if (fieldObject.getClass() != String.class) {
                            fehlerGefunden = pruefeObjektAufFehler(fieldObject, null, tiefe + 1) ? true
                                    : fehlerGefunden;
                        }
                    }
                } else {
                    // Collection, prfen ob fachliche Fehlerliste
                    ParameterizedType type = (ParameterizedType) field.getGenericType();
                    Class<?> collectionTypeArgument = (Class<?>) type.getActualTypeArguments()[0];
                    if (collectionTypeArgument.isAnnotationPresent(FachlicherFehler.class)) {
                        // Ist Fehlerliste, prfen ob nicht leer
                        Collection<?> collection = (Collection<?>) field.get(result);
                        if (collection != null && !collection.isEmpty()) {
                            // Fachliche Fehler in Fehlerliste gefunden
                            return true;
                        }
                    }
                }
            } catch (IllegalAccessException e) {
                // Nichts tun, Feld wird ignoriert
                LOGISY.debug("Feldzugriffsfehler: {}", e.getMessage());
            }
        }
    }

    // Die Klassen-Hierachie rekursiv nach oben prfen
    if (clazzToScan.getSuperclass() != null && !clazzToScan.getSuperclass().equals(Object.class)) {
        LOGISY.trace("{}> Climb up class hierarchy! Source {}, Target {}", StringUtils.repeat("-", tiefe),
                clazzToScan.getSimpleName(), clazzToScan.getSuperclass());
        fehlerGefunden =
                // Aufruf mit gleicher Tiefe, da Vererbung nach oben durchlaufen wird
                pruefeObjektAufFehler(result, clazzToScan.getSuperclass(), tiefe) ? true : fehlerGefunden;
    }

    return fehlerGefunden;
}

From source file:com.evolveum.midpoint.model.impl.dataModel.dot.DotModel.java

public String indent(int i) {
    return StringUtils.repeat("  ", i);
}

From source file:candr.yoclip.DefaultParserHelpFactoryTest.java

@Test
public void testHangingIndentWrap() {

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

    final int width = 30;
    final int indent = 10;

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

    StrBuilder builder = new StrBuilder();
    builder.appendln(StringUtils.repeat("abc", 10)).appendPadding(indent, ' ')
            .append(StringUtils.repeat("abc", 5));
    assertThat("!whitespace", testCase.hangingIndentWrap(StringUtils.repeat("abc", 15), indent, width),
            is(builder.toString()));/*w  ww .  j  a  va  2s.  c o m*/

    final String pangram = "The quick brown fox jumps over the lazy dog";
    builder.clear();
    builder.appendln("The quick brown fox jumps over").appendPadding(indent, ' ').append("the lazy dog");
    assertThat("pangram", testCase.hangingIndentWrap(pangram, indent, width), is(builder.toString()));

    final String newLines = "\nExpected text without indent.\n\nFollowed by more that is indented.\n";
    builder.clear();
    builder.appendNewLine().appendln("Expected text without indent.").appendNewLine().appendPadding(indent, ' ')
            .appendln("Followed by more").appendPadding(indent, ' ').appendln("that is indented.");
    assertThat("new lines", testCase.hangingIndentWrap(newLines, indent, width), is(builder.toString()));
}