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) 

Source Link

Document

Left pad a String with spaces (' ').

The String is padded to the size of size .

 StringUtils.leftPad(null, *)   = null StringUtils.leftPad("", 3)     = "   " StringUtils.leftPad("bat", 3)  = "bat" StringUtils.leftPad("bat", 5)  = "  bat" StringUtils.leftPad("bat", 1)  = "bat" StringUtils.leftPad("bat", -1) = "bat" 

Usage

From source file:org.apache.batchee.cli.command.Executions.java

@Override
public void doRun() {
    final List<JobExecution> executions = operator().getJobExecutions(new JobInstanceImpl(id));
    if (!executions.isEmpty()) {
        info("Executions of " + executions.iterator().next().getJobName() + " for instance " + id);
    }// ww w  . ja  va  2  s  .c  om

    info("execution id\t|\tbatch status\t|\texit status\t|\tstart time\t|\tend time");
    for (final JobExecution exec : executions) {
        info(String.format("%12d\t|\t%s\t|\t%s\t|\t%tc\t|\t%tc", exec.getExecutionId(),
                StringUtils.leftPad(exec.getBatchStatus() != null ? exec.getBatchStatus().toString() : "null",
                        12),
                StringUtils.leftPad(exec.getExitStatus(), 11), exec.getStartTime(), exec.getEndTime()));
    }
}

From source file:org.apache.batchee.cli.command.Status.java

@Override
public void doRun() {
    final JobOperator operator = operator();
    final Set<String> names = operator.getJobNames();
    if (names == null || names.isEmpty()) {
        info("No job");
    } else {/* w w  w.  java 2s. c o m*/
        info("     Name   \t|\texecution id\t|\tbatch status\t|\texit status\t|\tstart time\t|\tend time");
        for (final String name : names) {
            try {
                final JobExecution exec = new LinkedList<JobExecution>(
                        operator.getJobExecutions(new LinkedList<JobInstance>(
                                operator.getJobInstances(name, operator.getJobInstanceCount(name) - 1, 2))
                                        .getLast())).getLast();
                info(String.format("%s\t|\t%12d\t|\t%s\t|\t%s\t|\t%tc\t|\t%tc", StringUtils.leftPad(name, 12),
                        exec.getExecutionId(),
                        StringUtils.leftPad(
                                exec.getBatchStatus() != null ? exec.getBatchStatus().toString() : "null", 12),
                        StringUtils.leftPad(exec.getExitStatus(), 11), exec.getStartTime(), exec.getEndTime()));
            } catch (final NoSuchJobException nsje) {
                // no-op
            }
        }
    }
}

From source file:org.apache.mahout.classifier.RegressionResultAnalyzer.java

@Override
public String toString() {
    double sumActual = 0.0;
    double sumActualSquared = 0.0;
    double sumResult = 0.0;
    double sumResultSquared = 0.0;
    double sumActualResult = 0.0;
    double sumAbsolute = 0.0;
    double sumAbsoluteSquared = 0.0;
    int predictable = 0;
    int unpredictable = 0;

    for (Result res : results) {
        double actual = res.getActual();
        double result = res.getResult();
        if (Double.isNaN(result)) {
            unpredictable++;/*  w  w w.j  a v  a  2  s.c om*/
        } else {
            sumActual += actual;
            sumActualSquared += actual * actual;
            sumResult += result;
            sumResultSquared += result * result;
            sumActualResult += actual * result;
            double absolute = Math.abs(actual - result);
            sumAbsolute += absolute;
            sumAbsoluteSquared += absolute * absolute;
            predictable++;
        }
    }

    StringBuilder returnString = new StringBuilder();

    returnString.append("=======================================================\n");
    returnString.append("Summary\n");
    returnString.append("-------------------------------------------------------\n");

    if (predictable > 0) {
        double varActual = sumActualSquared - sumActual * sumActual / predictable;
        double varResult = sumResultSquared - sumResult * sumResult / predictable;
        double varCo = sumActualResult - sumActual * sumResult / predictable;

        double correlation;
        if (varActual * varResult <= 0) {
            correlation = 0.0;
        } else {
            correlation = varCo / Math.sqrt(varActual * varResult);
        }

        Locale.setDefault(Locale.US);
        NumberFormat decimalFormatter = new DecimalFormat("0.####");

        returnString.append(StringUtils.rightPad("Correlation coefficient", 40)).append(": ")
                .append(StringUtils.leftPad(decimalFormatter.format(correlation), 10)).append('\n');
        returnString.append(StringUtils.rightPad("Mean absolute error", 40)).append(": ")
                .append(StringUtils.leftPad(decimalFormatter.format(sumAbsolute / predictable), 10))
                .append('\n');
        returnString.append(StringUtils.rightPad("Root mean squared error", 40)).append(": ")
                .append(StringUtils
                        .leftPad(decimalFormatter.format(Math.sqrt(sumAbsoluteSquared / predictable)), 10))
                .append('\n');
    }
    returnString.append(StringUtils.rightPad("Predictable Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(predictable), 10)).append('\n');
    returnString.append(StringUtils.rightPad("Unpredictable Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(unpredictable), 10)).append('\n');
    returnString.append(StringUtils.rightPad("Total Regressed Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(results.size()), 10)).append('\n');
    returnString.append('\n');

    return returnString.toString();
}

From source file:org.apache.mahout.classifier.ResultAnalyzer.java

@Override
public String toString() {
    StringBuilder returnString = new StringBuilder();

    returnString.append('\n');
    returnString.append("=======================================================\n");
    returnString.append("Summary\n");
    returnString.append("-------------------------------------------------------\n");
    int totalClassified = correctlyClassified + incorrectlyClassified;
    double percentageCorrect = (double) 100 * correctlyClassified / totalClassified;
    double percentageIncorrect = (double) 100 * incorrectlyClassified / totalClassified;
    NumberFormat decimalFormatter = new DecimalFormat("0.####");

    returnString.append(StringUtils.rightPad("Correctly Classified Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(correctlyClassified), 10)).append('\t')
            .append(StringUtils.leftPad(decimalFormatter.format(percentageCorrect), 10)).append("%\n");
    returnString.append(StringUtils.rightPad("Incorrectly Classified Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(incorrectlyClassified), 10)).append('\t')
            .append(StringUtils.leftPad(decimalFormatter.format(percentageIncorrect), 10)).append("%\n");
    returnString.append(StringUtils.rightPad("Total Classified Instances", 40)).append(": ")
            .append(StringUtils.leftPad(Integer.toString(totalClassified), 10)).append('\n');
    returnString.append('\n');

    returnString.append(confusionMatrix);
    returnString.append("=======================================================\n");
    returnString.append("Statistics\n");
    returnString.append("-------------------------------------------------------\n");

    RunningAverageAndStdDev normStats = confusionMatrix.getNormalizedStats();
    returnString.append(StringUtils.rightPad("Kappa", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getKappa()), 10)).append('\n');
    returnString.append(StringUtils.rightPad("Accuracy", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getAccuracy()), 10))
            .append("%\n");
    returnString.append(StringUtils.rightPad("Reliability", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(normStats.getAverage() * 100.00000001), 10))
            .append("%\n");
    returnString.append(StringUtils.rightPad("Reliability (standard deviation)", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(normStats.getStandardDeviation()), 10))
            .append('\n');
    returnString.append(StringUtils.rightPad("Weighted precision", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getWeightedPrecision()), 10))
            .append('\n');
    returnString.append(StringUtils.rightPad("Weighted recall", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getWeightedRecall()), 10))
            .append('\n');
    returnString.append(StringUtils.rightPad("Weighted F1 score", 40))
            .append(StringUtils.leftPad(decimalFormatter.format(confusionMatrix.getWeightedF1score()), 10))
            .append('\n');

    if (hasLL) {// w  w  w  .  ja  v a  2s  .c o m
        returnString.append(StringUtils.rightPad("Log-likelihood", 30)).append("mean      : ")
                .append(StringUtils.leftPad(decimalFormatter.format(summarizer.getMean()), 10)).append('\n');
        returnString.append(StringUtils.rightPad("", 30)).append(StringUtils.rightPad("25%-ile   : ", 10))
                .append(StringUtils.leftPad(decimalFormatter.format(summarizer.getQuartile(1)), 10))
                .append('\n');
        returnString.append(StringUtils.rightPad("", 30)).append(StringUtils.rightPad("75%-ile   : ", 10))
                .append(StringUtils.leftPad(decimalFormatter.format(summarizer.getQuartile(3)), 10))
                .append('\n');
    }

    return returnString.toString();
}

From source file:org.apache.mahout.utils.clustering.AbstractClusterWriter.java

public static String getTopFeatures(Vector vector, String[] dictionary, int numTerms) {

    StringBuilder sb = new StringBuilder(100);

    for (Pair<String, Double> item : getTopPairs(vector, dictionary, numTerms)) {
        String term = item.getFirst();
        sb.append("\n\t\t");
        sb.append(StringUtils.rightPad(term, 40));
        sb.append("=>");
        sb.append(StringUtils.leftPad(item.getSecond().toString(), 20));
    }//from   ww  w .jav a2  s .  co m
    return sb.toString();
}

From source file:org.duracloud.common.util.EncryptionUtil.java

public EncryptionUtil(String key) throws DuraCloudRuntimeException {
    if (key == null) {
        throw new IllegalArgumentException("'key' parameter must be non-null");
    }/*w  w  w.  j  av  a  2  s.c o  m*/

    int keySize = DEFAULT_KEY.length();
    if (key.length() > keySize) {
        key = key.substring(0, keySize);
    }

    key = StringUtils.leftPad(key, keySize);

    this.keyBytes = key.getBytes();
    try {
        // Create cipher
        this.cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

        // Create Key
        DESKeySpec deskey = new DESKeySpec(this.keyBytes);
        this.key = new SecretKeySpec(deskey.getKey(), "DES");
    } catch (Exception e) {
        throw new DuraCloudRuntimeException(e);
    }
}

From source file:org.evosuite.ga.stoppingconditions.StoppingConditionImpl.java

/**
 * <p>getValueString</p>/*from  w ww.  j av  a  2 s.  co  m*/
 *
 * @return a {@link java.lang.String} object.
 */
public String getValueString() {
    String value = NumberFormat.getIntegerInstance().format(getCurrentValue());
    value = StringUtils.leftPad(value, 12);
    String limit = NumberFormat.getIntegerInstance().format(getLimit());
    limit = StringUtils.rightPad(limit, 12);
    return value + " / " + limit;
}

From source file:org.jpos.qi.system.SQLQueryObject.java

@Override
public String toString() {
    try {/* w  w w  .j a v  a 2s. co m*/
        Object res = DB.exec(db -> {
            StringBuilder sb = new StringBuilder("");
            for (int n = 0; n < queries.length; n++) {
                String query = queries[n];
                String title = titles[n];
                int mxrows = maxRows[n];
                sb.append(' ').append(title).append("\n\n");
                db.session().doWork(new Work() {
                    @Override
                    public void execute(Connection connection) throws SQLException {
                        PreparedStatement stmt = connection.prepareStatement(query);
                        ResultSet rs = stmt.executeQuery();
                        ResultSetMetaData md = rs.getMetaData();
                        int cols = md.getColumnCount();
                        String[] header = new String[cols];
                        int[] colsize = new int[cols];
                        for (int i = 1; i <= cols; i++) {
                            header[i - 1] = StringUtils.defaultIfEmpty(md.getColumnLabel(i),
                                    md.getColumnName(i));
                            colsize[i - 1] = header[i - 1].length();
                        }
                        int rows = 0;
                        String[][] out = new String[mxrows][cols];
                        while (rs.next() && rows < mxrows) {
                            for (int i = 1; i <= cols; i++) {
                                out[rows][i - 1] = rs.getString(i);
                                if (out[rows][i - 1] == null)
                                    out[rows][i - 1] = " ";
                                int l = out[rows][i - 1].length();
                                if (colsize[i - 1] < l)
                                    colsize[i - 1] = l;
                            }
                            rows++;
                        }
                        rs.close();
                        stmt.close();
                        StringBuilder sbSep = new StringBuilder(" ");
                        sb.append(' ');
                        for (int i = 1; i <= cols; i++) {
                            if (isNumericDataType(md.getColumnType(i)))
                                sb.append(StringUtils.leftPad(header[i - 1], colsize[i - 1]));
                            else
                                sb.append(StringUtils.rightPad(header[i - 1], colsize[i - 1]));
                            sbSep.append(StringUtils.repeat('-', colsize[i - 1]));
                            sb.append(' ');
                            sbSep.append(' ');
                        }
                        sb.append('\n');
                        sbSep.append('\n');
                        sb.append(sbSep);
                        for (int j = 0; j < rows; j++) {
                            sb.append(' ');
                            for (int i = 1; i <= cols; i++) {
                                if (isNumericDataType(md.getColumnType(i)))
                                    sb.append(StringUtils.leftPad(out[j][i - 1], colsize[i - 1]));
                                else
                                    sb.append(StringUtils.rightPad(out[j][i - 1], colsize[i - 1]));
                                sb.append(' ');
                            }
                            sb.append('\n');
                        }
                        sb.append(sbSep).append('\n');
                    }
                });
            }
            sb.append(" Last refreshed at ").append(new Date());
            return sb;
        });
        return res.toString();
    } catch (Exception e) {
        QI.getQI().getLog().error(e);
        return e.toString();
    }

}

From source file:org.kalypso.commons.java.util.StringUtilities.java

/**
 * Spans a string onto lines, thus it inserts NEWLINE chars at lineLength + 1 for each line. It firsts removes all
 * existing NEWLINE chars./*  w  w w.  j a  v a  2  s  . c o m*/
 * 
 * @param str
 *          the string to span
 * @param lineLength
 *          the number of chars one line must have
 * @param keepWords
 *          when true words are not cut at the end of the line but rather postponed on the next line
 * @return newly spaned string or null if str is null
 */
public static String spanOverLines(final String str, final int lineLength, final boolean keepWords,
        final int alignment) {
    if (str == null)
        return null;

    if (lineLength == 0)
        return str;

    str.replaceAll("\\n", ""); //$NON-NLS-1$ //$NON-NLS-2$

    final StringBuffer bf = new StringBuffer();
    int i = 0;
    while (true) {
        if (i + lineLength > str.length()) {
            String line = str.substring(i, str.length());
            if (alignment == StringUtilities.ALIGNMENT_LEFT)
                line = StringUtils.stripStart(line, null);
            if (alignment == StringUtilities.ALIGNMENT_RIGHT) {
                line = StringUtils.stripEnd(line, null);
                line = StringUtils.leftPad(line, lineLength);
            }
            bf.append(line);
            break;
        }

        int curLineLength = lineLength;
        if (keepWords && !Character.isWhitespace(str.charAt(i + lineLength - 2))
                && !Character.isWhitespace(str.charAt(i + lineLength - 1))
                && !Character.isWhitespace(str.charAt(i + lineLength))) {
            curLineLength = lineLength - 3;
            while (curLineLength > 0 && !Character.isWhitespace(str.charAt(i + curLineLength)))
                curLineLength--;

            if (curLineLength == 0)
                curLineLength = lineLength;
            if (curLineLength != lineLength)
                curLineLength++;
        }

        String line = str.substring(i, i + curLineLength);
        if (alignment == StringUtilities.ALIGNMENT_LEFT)
            line = StringUtils.stripStart(line, null);
        if (alignment == StringUtilities.ALIGNMENT_RIGHT) {
            line = StringUtils.stripEnd(line, null);
            line = StringUtils.leftPad(line, lineLength);
        }

        bf.append(line).append(System.getProperty("line.separator")); //$NON-NLS-1$

        i = i + curLineLength;
    }

    return bf.toString();
}

From source file:org.kuali.kra.timeandmoney.document.TimeAndMoneyDocument.java

@Override
public int compareTo(Object o) {
    if (this == o) {
        return 0;
    }//  w  ww  .ja  v  a2 s.  c  om
    if (o == null) {
        return 1;
    }
    TimeAndMoneyDocument comparator = (TimeAndMoneyDocument) o;
    String myKey = StringUtils.leftPad(getDocumentNumber(), 40);
    String otherKey = StringUtils.leftPad(comparator.getDocumentNumber(), 40);
    return myKey.compareTo(otherKey);
}