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) 

Source Link

Document

Left pad a String with spaces (' ').

Usage

From source file:de.codesourcery.eve.skills.ui.components.impl.RefiningComponent.java

protected void putRefiningResultsOnClipboard() {

    final StringBuffer text = new StringBuffer();

    text.append(StringUtils.rightPad("Item", 35)).append(StringUtils.rightPad("Volume", 15))
            .append(StringUtils.leftPad("Quantity", 15)).append(StringUtils.leftPad("Sell value", 15))
            .append("\n\n");

    final List<RefiningResult> rows = refiningResultsModel.myData;
    final DecimalFormat VOL = new DecimalFormat("###,###,###,###,###.0###");
    for (Iterator<RefiningResult> it = rows.iterator(); it.hasNext();) {
        final RefiningResult row = it.next();

        final double volume = row.getYourQuantityMinusStationTax() * row.getType().getVolume();

        text.append(StringUtils.rightPad(row.getType().getName(), 35))
                .append(StringUtils.leftPad(VOL.format(volume), 15))
                .append(StringUtils.leftPad("" + row.getYourQuantityMinusStationTax(), 15))
                .append(StringUtils.leftPad(AmountHelper.formatISKAmount(row.getSellValue()), 15));

        if (it.hasNext()) {
            text.append("\n");
        }//from ww w.  ja  v a 2  s .  c  om
    }

    new PlainTextTransferable(text).putOnClipboard();
}

From source file:com.grantingersoll.intell.clustering.KMeansClusteringEngine.java

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

    List<TermIndexWeight> vectorTerms = new ArrayList<TermIndexWeight>();

    Iterator<Vector.Element> iter = vector.iterateNonZero();
    while (iter.hasNext()) {
        Vector.Element elt = iter.next();
        vectorTerms.add(new TermIndexWeight(elt.index(), elt.get()));
    }//from  www .j  av a  2s .  c o  m

    // Sort results in reverse order (ie weight in descending order)
    Collections.sort(vectorTerms, new Comparator<TermIndexWeight>() {

        public int compare(TermIndexWeight one, TermIndexWeight two) {
            return Double.compare(two.weight, one.weight);
        }
    });

    Collection<Pair<String, Double>> topTerms = new LinkedList<Pair<String, Double>>();

    for (int i = 0; (i < vectorTerms.size()) && (i < numTerms); i++) {
        int index = vectorTerms.get(i).index;
        String dictTerm = dictionary[index];
        if (dictTerm == null) {
            log.error("Dictionary entry missing for {}", index);
            continue;
        }
        topTerms.add(new Pair<String, Double>(dictTerm, vectorTerms.get(i).weight));
    }

    StringBuilder sb = new StringBuilder(100);

    for (Pair<String, Double> item : topTerms) {
        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));
    }
    return sb.toString();
}

From source file:de.codesourcery.eve.skills.ui.components.impl.planning.ShoppingListComponent.java

private void putSelectedShoppingListOnClipboard() {

    final StringBuffer result = new StringBuffer();

    final ITreeNode selected = getSelectedTreeNode();
    if (selected == null) {
        return;/*from  w  w w. ja v  a2s  .  c o m*/
    }

    final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

    ShoppingList list = null;
    if (selected.getValue() instanceof ShoppingList) {
        list = (ShoppingList) selected.getValue();
    } else if (selected.getValue() instanceof ShoppingListEntry) {
        final ShoppingListEntry entry = (ShoppingListEntry) selected.getValue();
        list = entry.getShoppingList();
    }

    if (list == null) {
        return;
    }

    result.append(list.getTitle()).append(Misc.newLine());
    if (!StringUtils.isBlank(list.getDescription())) {
        result.append(Misc.newLine()).append(list.getDescription()).append(Misc.newLine().twice());
    }

    final DecimalFormat quantityFormat = new DecimalFormat("###,###,###,###,##0");

    for (Iterator<ShoppingListEntry> it = list.iterator(); it.hasNext();) {
        final ShoppingListEntry entry = it.next();

        result.append(StringUtils.rightPad(entry.getType().getName(), 30))
                .append(StringUtils.leftPad(quantityFormat.format(entry.getQuantity()), 20));

        if (it.hasNext()) {
            result.append(Misc.newLine());
        }
    }

    clipboard.setContents(new PlainTextTransferable(result.toString()), null);
}

From source file:gov.medicaid.process.enrollment.sync.FlatFileExporter.java

/**
 * Converts the given date to the export format.
 * // w ww  . j  a  va  2  s. c  o m
 * @param value the value to convert
 * @param width the width of the field
 * @return the formatted data
 */
private String fixWidthDate(Date value, int width) {
    return StringUtils.leftPad(new SimpleDateFormat("yyyy-MM-dd").format(value), width);
}

From source file:gov.medicaid.process.enrollment.sync.FlatFileExporter.java

/**
 * Converts the given object to the export format.
 * /*  w  w  w  .j  a  va 2 s . c  o m*/
 * @param value the value to convert
 * @param width the width of the field
 * @return the formatted data
 */
private String fixWidth(String value, int width) {
    if (value != null) {
        return value.length() > width ? value.substring(0, width) : StringUtils.leftPad(value, width);
    }
    return StringUtils.leftPad("", width);
}

From source file:com.twinsoft.convertigo.eclipse.views.loggers.EngineLogView.java

private boolean getLogs() {
    try {/*from   ww  w  .  ja v  a2s.  c  o  m*/
        JSONArray logs = logManager.getLines();
        boolean interrupted = false;
        while (logs.length() == 0 && !interrupted && Thread.currentThread() == logViewThread) {
            synchronized (appender) {
                try {
                    appender.wait(300);
                } catch (InterruptedException e) {
                    interrupted = true;
                }
            }

            // Detect if the view has been closed
            if (Thread.currentThread() != logViewThread) {
                return false;
            }
            logs = logManager.getLines();
        }

        HashMap<String, String> allExtras = new HashMap<String, String>();

        for (int i = 0; i < logs.length(); i++) {
            JSONArray logLine = (JSONArray) logs.get(i);

            String dateTime = logLine.getString(1);
            String[] dateTimeParts = dateTime.split(" ");
            String date = dateTimeParts[0];
            String time = dateTimeParts[1];

            String deltaTime;
            try {
                long currentDate = DATE_FORMAT.parse(dateTime).getTime();
                if (lastLogTime < 0) {
                    deltaTime = "--";
                } else {
                    long delta = currentDate - lastLogTime;
                    lastLogTime = currentDate;
                    if (delta < 1000) {
                        deltaTime = StringUtils.leftPad(delta + " ms", 8);
                    } else if (delta < 10000) {
                        deltaTime = StringUtils.leftPad(Math.floor(delta / 10.0) / 100.0 + " s ", 8);
                    } else {
                        deltaTime = StringUtils.leftPad((int) Math.floor(delta / 1000.0) + " s ", 8);
                    }
                }
                lastLogTime = currentDate;
            } catch (ParseException e) {
                deltaTime = "n/a";
            }

            int len = logLine.length();
            for (int j = 5; j < len; j++) {
                String extra = logLine.getString(j);
                int k = extra.indexOf("=");
                allExtras.put(extra.substring(0, k), extra.substring(k + 1));
            }

            // Build the message lines
            String message = logLine.getString(4);
            String[] messageLines = message.split("\n");
            if (messageLines.length > 1) {
                boolean firstLine = true;
                for (String messageLine : messageLines) {
                    logLines.add(new LogLine(logLine.getString(0), date, time, deltaTime, logLine.getString(2),
                            logLine.getString(3), messageLine, !firstLine, counter, logLine.getString(4),
                            allExtras));
                    counter++;
                    firstLine = false;
                }
            } else {
                logLines.add(new LogLine(logLine.getString(0), date, time, deltaTime, logLine.getString(2),
                        logLine.getString(3), logLine.getString(4), false, counter, logLine.getString(4),
                        allExtras));
                counter++;
            }
        }
    } catch (JSONException e) {
        ConvertigoPlugin.logException(e, "Unable to process received Engine logs", false);
    } catch (Exception e) {
        ConvertigoPlugin.logException(e,
                "Error while loading the Engine logs (" + e.getClass().getCanonicalName() + ")", false);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e1) {
        }
    }
    logManager.setContinue(true);
    return true;
}

From source file:edu.cornell.kfs.fp.batch.service.impl.AdvanceDepositServiceImpl.java

private List<String> addRMRAndNTELinesToNotes(AchIncomeFileTransaction achIncomeFileTransaction,
        StringBuilder notes) {//from  ww  w  . ja  v  a 2s. c  o  m
    List<String> achNotes = new ArrayList<>();

    boolean header = true;
    Integer lineCount = 1;

    for (AchIncomeFileTransactionOpenItemReference openItemReference : achIncomeFileTransaction
            .getOpenItemReferences()) {
        int leftNoteSize = MAX_NOTE_SIZE - notes.length();
        if ((notes.length() >= MAX_NOTE_SIZE) || (leftNoteSize <= MIN_NOTE_SIZE)) {
            achNotes.add(notes.toString());
            notes = new StringBuilder();
            header = true;
        }
        String type = openItemReference.getType();
        if (CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_REFERENCE_TYPE_CR.equals(type)
                || CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_REFERENCE_TYPE_IV.equals(type)
                || CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_REFERENCE_TYPE_OI.equals(type)) {
            if (header) {
                notes.append(StringUtils.rightPad("LINE",
                        CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_NOTE_LINE_COLUMN_WIDTH));
                notes.append(StringUtils.rightPad("INVOICE NUMBER",
                        CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_NOTE_INVOICE_NUMBER_COLUMN_WIDTH));
                notes.append(StringUtils.rightPad("NETAMOUNT PAID",
                        CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_NOTE_NET_AMOUNT_COLUMN_WIDTH));
                notes.append(StringUtils.rightPad("INVOICE AMOUNT",
                        CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_NOTE_INVOICE_AMOUNT_COLUMN_WIDTH));
                notes.append("\n");
                header = false;
            }

            notes.append(StringUtils.rightPad(getFormattedAmount("00000", lineCount),
                    CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_NOTE_LINE_COLUMN_WIDTH));
            notes.append(StringUtils.rightPad(openItemReference.getInvoiceNumber(),
                    CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_NOTE_INVOICE_NUMBER_COLUMN_WIDTH));
            if (openItemReference.getNetAmount() != null) {
                notes.append(StringUtils.leftPad(
                        getFormattedAmount("##,##,###.00", openItemReference.getNetAmount()),
                        CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_NOTE_NET_AMOUNT_COLUMN_WIDTH));

            }
            if (openItemReference.getInvoiceAmount() != null) {
                notes.append(StringUtils.leftPad(
                        getFormattedAmount("##,##,###.00", openItemReference.getInvoiceAmount()),
                        CuFPConstants.AchIncomeFileTransactionOpenItemReference.RMR_NOTE_INVOICE_AMOUNT_COLUMN_WIDTH));
            }
            notes.append("\n");
            lineCount++;
        }
    }

    List<AchIncomeFileTransactionNote> fileTransactionNotes = achIncomeFileTransaction.getNotes();
    for (AchIncomeFileTransactionNote fileTransactionNote : fileTransactionNotes) {
        if (fileTransactionNote.getType() != null) {
            String nteTxt = fileTransactionNote.getType().toUpperCase() + ": " + fileTransactionNote.getValue();
            int notesPlusNoteTxtLength = nteTxt.length() + notes.length();
            if (notesPlusNoteTxtLength >= MAX_NOTE_SIZE) {
                achNotes.add(notes.toString());
                notes = new StringBuilder();
            }
            notes.append(nteTxt.trim());
            notes.append("\n");
        }

    }
    achNotes.add(notes.toString());

    return achNotes;
}

From source file:edu.cornell.kfs.fp.batch.service.impl.AdvanceDepositServiceImpl.java

private String getEmailMessageText(AchIncomeFile achIncomeFile, String payerMessage) {
    StringBuilder message = new StringBuilder();

    int totalPostedTransation = achTotalPostedTransactions + wiredTotalPostedTransactions;
    KualiDecimal totalPostedTransactionAmount = achTotalPostedTransactionAmount
            .add(wiredTotalPostedTransactionAmount);

    String fileDateTime;/*from   ww  w.  j a v a2  s .  co  m*/
    try {
        fileDateTime = getFormattedTimestamp(achIncomeFile, "fileDate/Time").toString();
    } catch (FormatException e) {
        // use the original file Date/Time string if encountered invalid format
        fileDateTime = achIncomeFile.getFileDate() + " " + achIncomeFile.getFileTime();
    }

    message.append("File Date: " + fileDateTime);
    message.append("\n");
    message.append("                    ");
    message.append("COUNT               ");
    message.append("        AMOUNT     ");
    message.append("\n");
    message.append(StringUtils.rightPad("ACH Posted", 20));
    message.append(StringUtils.rightPad(achTotalPostedTransactions + "", 20));
    message.append(
            StringUtils.leftPad(getFormattedAmount("##,##,##0.00", achTotalPostedTransactionAmount), 20));
    message.append("\n");
    message.append(StringUtils.rightPad("Wire Posted", 20));
    message.append(StringUtils.rightPad(wiredTotalPostedTransactions + "", 20));
    message.append(
            StringUtils.leftPad(getFormattedAmount("##,##,##0.00", wiredTotalPostedTransactionAmount), 20));
    message.append("\n");
    message.append(StringUtils.rightPad("Total Posted", 20));
    message.append(StringUtils.rightPad(totalPostedTransation + "", 20));
    message.append(StringUtils.leftPad(getFormattedAmount("##,##,##0.00", totalPostedTransactionAmount), 20));
    message.append("\n");
    message.append("\n");
    message.append(StringUtils.rightPad("ACH Skipped", 20));
    message.append(StringUtils.rightPad(achTotalSkippedTransactions + "", 20));
    message.append(
            StringUtils.leftPad(getFormattedAmount("##,##,##0.00", achTotalSkippedTransactionAmount), 20));
    message.append("\n");
    message.append(StringUtils.rightPad("Wire Skipped", 20));
    message.append(StringUtils.rightPad(wiredTotalSkippedTransactions + "", 20));
    message.append(
            StringUtils.leftPad(getFormattedAmount("##,##,##0.00", wiredTotalSkippedTransactionAmount), 20));
    message.append("\n");
    if (StringUtils.isNotBlank(payerMessage)) {
        message.append("\n");
        message.append("Transactions Missing Payer Name: ");
        message.append("\n");
        message.append(payerMessage);
    }
    return message.toString();
}

From source file:gtu._work.etc.EnglishTester.java

void ifIsNumberSort(List<String> list) {
    boolean allNumberOk = true;
    int length = 0;
    for (String val : list) {
        if (!StringUtils.isNumeric(val)) {
            allNumberOk = false;/*  w  ww .j ava  2 s. co m*/
            break;
        }
        length = Math.max(length, val.length());
    }
    if (allNumberOk == false) {
        return;
    }
    final int finalLen = length;
    Collections.sort(list, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            o1 = StringUtils.leftPad(o1, finalLen);
            o2 = StringUtils.leftPad(o2, finalLen);
            return o1.compareTo(o2);
        }
    });
}

From source file:org.apache.cocoon.generation.VelocityGenerator.java

/**
 * Generate XML data using Velocity template.
 *
 * @see org.apache.cocoon.generation.Generator#generate()
 *///from  w w w.ja  va 2  s.co  m
public void generate() throws IOException, SAXException, ProcessingException {
    // Guard against calling generate before setup.
    if (!activeFlag) {
        throw new IllegalStateException("generate called on sitemap component before setup.");
    }

    SAXParser parser = null;
    StringWriter w = new StringWriter();
    try {
        parser = (SAXParser) this.manager.lookup(SAXParser.ROLE);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Processing File: " + super.source);
        }
        if (!tmplEngineInitialized) {
            tmplEngine.init();
            tmplEngineInitialized = true;
        }
        /* lets render a template */
        this.tmplEngine.mergeTemplate(super.source, velocityContext, w);

        InputSource xmlInput = new InputSource(new StringReader(w.toString()));
        xmlInput.setSystemId(super.source);
        parser.parse(xmlInput, this.xmlConsumer);
    } catch (IOException e) {
        getLogger().warn("VelocityGenerator.generate()", e);
        throw new ResourceNotFoundException("Could not get Resource for VelocityGenerator", e);
    } catch (SAXParseException e) {
        int line = e.getLineNumber();
        int column = e.getColumnNumber();
        if (line <= 0) {
            line = Integer.MAX_VALUE;
        }
        BufferedReader reader = new BufferedReader(new StringReader(w.toString()));
        StringBuffer message = new StringBuffer(e.getMessage());
        message.append(" In generated document:\n");
        for (int i = 0; i < line; i++) {
            String lineStr = reader.readLine();
            if (lineStr == null) {
                break;
            }
            message.append(lineStr);
            message.append("\n");
        }
        if (column > 0) {
            message.append(StringUtils.leftPad("^\n", column + 1));
        }
        SAXException pe = new SAXParseException(message.toString(), e.getPublicId(),
                "(Document generated from template " + e.getSystemId() + ")", e.getLineNumber(),
                e.getColumnNumber(), null);
        getLogger().error("VelocityGenerator.generate()", pe);
        throw pe;
    } catch (SAXException e) {
        getLogger().error("VelocityGenerator.generate()", e);
        throw e;
    } catch (ServiceException e) {
        getLogger().error("Could not get parser", e);
        throw new ProcessingException("Exception in VelocityGenerator.generate()", e);
    } catch (ProcessingException e) {
        throw e;
    } catch (Exception e) {
        getLogger().error("Could not get parser", e);
        throw new ProcessingException("Exception in VelocityGenerator.generate()", e);
    } finally {
        this.manager.release(parser);
    }
}