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

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

Introduction

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

Prototype

public static String center(final String str, final int size) 

Source Link

Document

Centers a String in a larger String of size size using the space character (' ').

If the size is less than the String length, the String is returned.

Usage

From source file:br.usp.poli.lta.cereda.macro.Application.java

/**
 * Mtodo principal.//from   ww  w .j a v a  2s .co  m
 * @param args Argumentos de linha de comando.
 */
public static void main(String[] args) {

    // imprime banner
    System.out.println(StringUtils.repeat("-", 50));
    System.out.println(StringUtils.center("Expansor de macros", 50));
    System.out.println(StringUtils.repeat("-", 50));
    System.out.println(StringUtils.center("Laboratrio de linguagens e tcnicas adaptativas", 50));
    System.out.println(StringUtils.center("Escola Politcnica - Universidade de So Paulo", 50));
    System.out.println();

    try {

        // faz o parsing dos argumentos de linha de comando
        CLIParser parser = new CLIParser(args);
        Pair<String, File> pair = parser.parse();

        // se o par no  nulo,  possvel prosseguir com a expanso
        if (pair != null) {

            // obtm a expanso do texto fornecido na entrada
            String output = MacroExpander.parse(pair.getFirst());

            // se foi definido um arquivo de sada, grava a expanso do
            // texto nele, ou imprime o resultado no terminal, caso
            // contrrio
            if (pair.getSecond() != null) {
                FileUtils.writeStringToFile(pair.getSecond(), output, Charset.forName("UTF-8"));
                System.out.println("Arquivo gerado com sucesso.");
            } else {
                System.out.println(output);
            }

        } else {

            // verifica se a execuo corresponde a uma chamada ao editor
            // embutido de macros
            if (parser.isEditor()) {

                // cria o editor e exibe
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        DisplayUtils.init();
                        Editor editor = new Editor();
                        editor.setVisible(true);
                    }
                });
            }
        }
    } catch (Exception exception) {

        // ocorreu uma exceo, imprime a mensagem de erro
        System.out.println(StringUtils.rightPad("ERRO: ", 50, "-"));
        System.out.println(WordUtils.wrap(exception.getMessage(), 50));
        System.out.println(StringUtils.repeat(".", 50));
    }
}

From source file:edu.usc.leqa.Main.java

/**
 * The main method for LEQA./*w w w. jav  a  2s  .c  o m*/
 *
 * @param args the command line arguments
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
    long start, actual = 0, estimated = 0;

    //      args = "-f ../sample_inputs/fabric.xml-t ../sample_inputs/tech.xml -i ../sample_inputs/tfc/8bitadder.tfc".split("\\s");
    parseInputs(args);
    // -s 0.001 

    /*
     * Parsing inputs: fabric, tech & qasm files
     * LEQA uses parsers of QSPR
     */
    System.out.println("Parsing technology and fabric files...");
    start = System.currentTimeMillis();
    layout = LayoutParser.parse(techFileAddr, fabricFileAddr);

    /* Converting TFC to QASM if TFC is provided. */
    String inputExtension = inputFileAddr.substring(inputFileAddr.lastIndexOf('.') + 1);
    if (inputExtension.compareToIgnoreCase("TFC") == 0) {
        System.out.println("TFC file is provided. Converting to QASM...");
        String qasmFileAddr = inputFileAddr.substring(0, inputFileAddr.lastIndexOf('.')) + ".qasm";

        if (TFCParser.parse(inputFileAddr, qasmFileAddr) == false) {
            System.err.println("Failed to convert " + inputFileAddr + " to QASM format.");
            System.exit(-1);
        }

        inputFileAddr = qasmFileAddr;
    } else if (inputExtension.compareToIgnoreCase("QASM") != 0) {
        System.err
                .println("Extension " + inputExtension + " is not supported! Only qasm and tfc are supported.");
        System.exit(-1);
    }

    /* Parsing the QASM file */
    System.out.println("Parsing QASM file...");
    qasm = QASMParser.QASMParser(inputFileAddr, layout);

    if (qasm == null || layout == null)
        System.exit(-1);
    parseRuntime = (System.currentTimeMillis() - start) / 1000.0;

    /*
     * Invoking LEQA for estimating the latency
     */
    System.out.println("Invoking LEQA...");
    start = System.currentTimeMillis();
    estimated = LEQA.leqa(qasm, layout, speed);
    leqaRuntime = (System.currentTimeMillis() - start) / 1000.0;

    /*
     * Invoking HL-QSPR for calculating the actual latency 
     * This is for comparison only. It can be commented out
     */
    if (!RuntimeConfig.SKIP) {
        System.out.println("Invoking QSPR...");
        start = System.currentTimeMillis();
        actual = QSPR.center(eds, layout, qasm);
        QSPRRuntime = (System.currentTimeMillis() - start) / 1000.0;
    }

    /*
     * Printing the results
     */
    int separatorLength = 30;
    System.out.println();
    System.out.println(StringUtils.center("Results", separatorLength));
    System.out.println(StringUtils.repeat('-', separatorLength));

    System.out.println("Estimated value:\t" + estimated);
    if (!RuntimeConfig.SKIP) {
        System.out.println("Actual value:\t\t" + actual);
        System.out.printf("Error:\t\t\t%.2f%%" + lineSeparator,
                (Math.abs(estimated - actual) * 100.0 / actual));
    }
    System.out.println(StringUtils.repeat('-', separatorLength));

    System.out.println("Parsing overhead:\t" + parseRuntime + "s");
    System.out.println("LEQA runtime:\t\t" + leqaRuntime + "s");
    if (!RuntimeConfig.SKIP) {
        System.out.println("QSPR time:\t\t" + QSPRRuntime + "s");
        System.out.printf("Speed up:\t\t%.2f" + lineSeparator, QSPRRuntime / leqaRuntime);
    }
}

From source file:edu.kit.dama.dataworkflow.util.DataWorkflowTaskUtils.java

/**
 * Print the provided list of DataWorkflow tasks to StdOut, either in a basic
 * tabular view or in verbose mode, in a detailed representation.
 *
 * @param pTasks The list of tasks to print out.
 * @param pVerbose TRUE = print detailed view, FALSE = print basic tabular
 * view.// www  .ja v a2 s .c  o  m
 */
public static void printTaskList(List<DataWorkflowTask> pTasks, boolean pVerbose) {
    if (!pVerbose) {
        //do table listing
        //Headers: ID | STATUS | LAST_MODIFIED
        //Lengths: 10 | 34 | 34
        StringBuilder listing = new StringBuilder();
        listing.append(StringUtils.center("Task ID", 10)).append("|").append(StringUtils.center("Status", 34))
                .append("|").append(StringUtils.center("Last Modified", 34)).append("\n");
        for (DataWorkflowTask task : pTasks) {
            listing.append(StringUtils.center(Long.toString(task.getId()), 10)).append("|")
                    .append(StringUtils.center(task.getStatus().toString(), 34)).append("|")
                    .append(StringUtils.center(new SimpleDateFormat().format(task.getLastUpdate()), 34))
                    .append("\n");
        }
        System.out.println(listing.toString());
    } else {
        //do detailed listing
        //ID: <ID>     Status: <STATUS>  Last Update: <LAST_UPDATE>
        //Config: <CONFIG_ID> Environment: <ID> Predecessor: <ID>
        //Group: <GID> Executor: <UID> Contact: <EMAIL>
        //Investigation: <ID>
        //InputDir: <URL>
        //OutputDir: <URL>              
        //WorkingDir: <URL>              
        //TempDir: <URL>
        //Input Objects         
        // Object | View 
        //  OID 1 | default
        //  OID 2 | default
        //Transfers          
        // Object | TransferId 
        //  OID 1 | 123
        //--------------------------------------------------------------
        StringBuilder builder = new StringBuilder();
        for (DataWorkflowTask task : pTasks) {
            builder.append(StringUtils.rightPad("Id: " + task.getId(), 40))
                    .append(StringUtils.rightPad(
                            "Predecessor: "
                                    + ((task.getPredecessor() != null) ? task.getPredecessor().getId() : "-"),
                            40))
                    .append("\n").append(StringUtils.rightPad("Status: " + task.getStatus(), 40))
                    .append(StringUtils.rightPad(
                            "Last Update: " + new SimpleDateFormat().format(task.getLastUpdate()), 40))
                    .append("\n")
                    .append(StringUtils.rightPad("Configuration: "
                            + ((task.getConfiguration() != null) ? task.getConfiguration().getId() : "-"), 40))
                    .append(StringUtils.rightPad("Environment: "
                            + ((task.getExecutionEnvironment() != null) ? task.getExecutionEnvironment().getId()
                                    : "-"),
                            40))
                    .append("\n").append(StringUtils.rightPad("Group: " + task.getExecutorGroupId(), 40))
                    .append(StringUtils.rightPad("User: " + task.getExecutorId(), 40)).append("\n")
                    .append(StringUtils.rightPad("Contact UserId: "
                            + ((task.getContactUserId() != null) ? task.getContactUserId() : "-"), 80))
                    .append("\n")
                    .append(StringUtils.rightPad("InvestigationId: " + task.getInvestigationId(), 80))
                    .append("\n").append(StringUtils.rightPad("Input Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getInputDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Output Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getOutputDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Working Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getWorkingDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Temp Dir:", 15))
                    .append(StringUtils.abbreviateMiddle(task.getTempDirectoryUrl(), "...", 65)).append("\n")
                    .append(StringUtils.rightPad("Input Objects:", 80)).append("\n")
                    .append(StringUtils.center("ObjectId", 39)).append("|")
                    .append(StringUtils.center("View", 40)).append("\n");
            try {
                Properties objectViewMap = task.getObjectViewMapAsObject();
                Set<Entry<Object, Object>> entries = objectViewMap.entrySet();
                if (entries.isEmpty()) {
                    builder.append(StringUtils.center("---", 39)).append("|")
                            .append(StringUtils.center("---", 40)).append("\n");
                } else {
                    for (Entry<Object, Object> entry : entries) {
                        builder.append(StringUtils.center((String) entry.getKey(), 39)).append("|")
                                .append(StringUtils.center((String) entry.getValue(), 40)).append("\n");
                    }
                }
            } catch (IOException ex) {
                LOGGER.error("Failed to deserialize object-view map of DataWorkflow task " + task.getId(), ex);
                builder.append(StringUtils.center("---", 39)).append("|").append(StringUtils.center("---", 40))
                        .append("\n");
            }
            builder.append(StringUtils.rightPad("Transfers:", 80)).append("\n")
                    .append(StringUtils.center("ObjectId", 39)).append("|")
                    .append(StringUtils.center("TransferId", 40)).append("\n");
            try {
                Properties objectTransferMap = task.getObjectTransferMapAsObject();
                Set<Entry<Object, Object>> entries = objectTransferMap.entrySet();
                if (entries.isEmpty()) {
                    builder.append(StringUtils.center("---", 39)).append("|")
                            .append(StringUtils.center("---", 40)).append("\n");
                } else {
                    for (Entry<Object, Object> entry : entries) {
                        builder.append(StringUtils.center((String) entry.getKey(), 39)).append("|")
                                .append(StringUtils.center((String) entry.getValue(), 40)).append("\n");
                    }
                }
            } catch (IOException ex) {
                LOGGER.error("Failed to deserialize object-transfer map of DataWorkflow task " + task.getId(),
                        ex);
                builder.append(StringUtils.center("---", 39)).append("|").append(StringUtils.center("---", 40))
                        .append("\n");
            }
            //add closing line
            builder.append(StringUtils.leftPad("", 80, '-')).append("\n");
        }
        System.out.println(builder.toString());
    }
}

From source file:kenh.expl.functions.Center.java

public String process(String str, int size) {
    return StringUtils.center(str, size);
}

From source file:de.tor.tribes.ui.renderer.TendencyTableCellRenderer.java

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
    JLabel label = (JLabel) c;
    Integer val = (Integer) value;
    String text = "";
    if (val == 0) {
        label.setIcon(yellow);// ww  w. j  a  va2  s  .  c o  m
    } else if (val > 0) {
        label.setIcon(red);
        text = "(+ " + val + ")";
    } else if (val < 0) {
        label.setIcon(green);
        text = "(" + val + ")";
    }
    label.setText(StringUtils.center(text, 9));
    return label;
}

From source file:edu.kit.dama.util.update.types.LibraryDiffInformation.java

@Override
public String toString() {
    StringBuilder b = new StringBuilder();
    String caption = "Library Diff Information";
    int maxWidth = 72;
    b.append(StringUtils.center(caption, maxWidth)).append("\n");
    b.append(StringUtils.rightPad("", maxWidth, "-")).append("\n");
    for (JavaLibrary lib : added) {
        b.append(StringUtils.abbreviateMiddle("(+) " + lib, "[...]", maxWidth)).append("\n");
    }/*from  ww w  .j  a v a2s.  c  om*/
    if (!changed.isEmpty()) {
        b.append("\n");
    }
    for (JavaLibrary lib : changed) {
        b.append(StringUtils.abbreviateMiddle("(U) " + lib, "[...]", maxWidth)).append("\n");
    }
    if (!unknown.isEmpty()) {
        b.append("\n");
    }
    for (JavaLibrary lib : unknown) {
        b.append(StringUtils.abbreviateMiddle("(?) " + lib, "[...]", maxWidth)).append("\n");
    }
    if (!deprecated.isEmpty()) {
        b.append("\n");
    }
    for (JavaLibrary lib : deprecated) {
        b.append(StringUtils.abbreviateMiddle("(-) " + lib, "[...]", maxWidth)).append("\n");
    }
    if (!ignored.isEmpty()) {
        b.append("\n");
    }
    for (File file : ignored) {
        b.append(StringUtils.abbreviateMiddle("(X) " + file.getAbsolutePath(), "[...]", maxWidth)).append("\n");
    }
    b.append("\n");
    b.append(StringUtils.rightPad("", maxWidth, "-")).append("\n");
    b.append("Added     : ").append(StringUtils.leftPad(String.valueOf(added.size()), 6)).append("\n");
    b.append("Changed   : ").append(StringUtils.leftPad(String.valueOf(changed.size()), 6)).append("\n");
    b.append("Deprecated: ").append(StringUtils.leftPad(String.valueOf(deprecated.size()), 6)).append("\n");
    b.append("Unknown   : ").append(StringUtils.leftPad(String.valueOf(unknown.size()), 6)).append("\n");
    b.append("Snapshots : ").append(StringUtils.leftPad(String.valueOf(detectedSnapshots), 6)).append("\n");
    b.append("Ignored   : ").append(StringUtils.leftPad(String.valueOf(ignored.size()), 6)).append("\n");
    b.append("Unchanged : ").append(StringUtils.leftPad(String.valueOf(unchanged.size()), 6)).append("\n");
    b.append(StringUtils.rightPad("", maxWidth, "-")).append("\n");
    return b.toString();
}

From source file:net.morimekta.idltool.cmd.RemoteList.java

@Override
public void execute(IdlTool idlTool) throws IOException {
    Meta localMeta = idlTool.getLocalMeta();

    boolean first = true;

    for (String repository : idlTool.getIdl().getRepositories()) {
        try {//from  w ww.  ja v a  2 s. c om
            Meta meta = idlTool.getRepositoryMeta(repository);
            int longestRemote = Math.max(30,
                    meta.getRemotes().keySet().stream().mapToInt(String::length).max().orElse(0));

            if (first) {
                first = false;
            } else {
                System.out.println();
            }

            if (meta.getRemotes().isEmpty()) {
                System.out.println(format("%s%s%s is empty.", new Color(Color.YELLOW, Color.BOLD), repository,
                        Color.CLEAR));
                continue;
            }

            System.out.println(format("%s%s%s", Color.GREEN, repository, Color.CLEAR));
            System.out.println(format("%s%s - %s - %s%s", new Color(Color.YELLOW, Color.BOLD),
                    StringUtils.center("<<-- remote -->>    ", longestRemote),
                    StringUtils.center("remote date", 19), StringUtils.center("local date", 19), Color.CLEAR));

            for (Map.Entry<String, Remote> remoteEntry : meta.getRemotes().entrySet().stream()
                    .sorted(comparator()).collect(Collectors.toList())) {
                Remote local = localMeta.getRemotes().get(remoteEntry.getKey());

                boolean change = false;
                if (local != null && remoteEntry.getValue().getTime() != local.getTime()) {
                    change = true;
                }

                System.out.println(format("%s%s - %s - %s%s", change ? Color.YELLOW : Color.CLEAR,
                        StringUtils.rightPad(remoteEntry.getKey(), longestRemote),
                        StringUtils.rightPad(formatAgo(remoteEntry.getValue().getTime()), 19),
                        local == null ? "" : formatAgo(local.getTime()), Color.CLEAR));
            }
        } catch (Exception e) {
            System.out.println("Bad repository " + repository + ": " + e.getMessage());
        }
    }
}

From source file:com.blackducksoftware.integration.eclipseplugin.views.providers.DependencyNumVulnColumnLabelProvider.java

@Override
public void styleCell(ViewerCell cell) {
    if (cell.getText().equals(VALUE_UNKNOWN)) {
        cell.setText("");
        return;//from  w ww. j  a v  a  2 s  .com
    }
    String[] vulnChunks = cell.getText().split(":");
    cell.setFont(JFaceResources.getTextFont());
    Display display = Display.getCurrent();
    final String noVulns = " 0 ";
    final Color textColor = display.getSystemColor(SWT.COLOR_WHITE);
    final Color highColor = decodeHex(display, "#b52b24");
    final Color mediumColor = decodeHex(display, "#eca4a0");
    final Color lowColor = decodeHex(display, "#999999");
    final Color invisible = display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND);
    final Color[] vulnColors = new Color[] { highColor, mediumColor, lowColor };
    StyleRange[] styleRanges = new StyleRange[vulnChunks.length];
    int lastLabelEnd = 0;
    cell.setText(String.format("%1$-5s %2$-5s %3$-5s", StringUtils.center(vulnChunks[0], 5),
            StringUtils.center(vulnChunks[1], 5), StringUtils.center(vulnChunks[2], 5)));
    for (int i = 0; i < vulnChunks.length; i++) {
        int labelStart = cell.getText().indexOf(vulnChunks[i], lastLabelEnd);
        int labelSize = vulnChunks[i].length();
        if (vulnChunks[i].equals(noVulns)) {
            styleRanges[i] = new StyleRange(labelStart, labelSize, invisible, invisible);
        } else {
            styleRanges[i] = new StyleRange(labelStart, labelSize, textColor, vulnColors[i]);
        }
        lastLabelEnd = labelStart + labelSize;
    }
    cell.setStyleRanges(styleRanges);
}

From source file:de.vandermeer.skb.interfaces.transformers.textformat.String_To_Centered.java

@Override
default StrBuilder transform(String s) {
    IsTransformer.super.transform(s);
    StrBuilder ret = (this.getBuilderForAppend() == null) ? new StrBuilder(this.getLength())
            : this.getBuilderForAppend();

    // set string and replace all inner ws with required character
    String center = (s == null) ? "" : s;
    center = center.replace(' ', this.getInnerWsChar());

    //get a char[] with a centered string, using paddingLedft in left and right side
    char[] car = StringUtils.center(center, this.getLength()).toCharArray();

    //change all right padding chars to the actual right padding char
    for (int i = car.length - 1; i > 0; i--) {
        if (car[i] == ' ') {
            car[i] = this.getRightPaddingChar();
        } else {/*from www  . j a  v a  2  s .com*/
            break;
        }
    }

    //change all remaining tmp padding chars to the actual left padding char
    for (int i = 0; i < car.length; i++) {
        if (car[i] == ' ') {
            car[i] = this.getLeftPaddingChar();
        } else {
            break;
        }
    }

    //add this new string to the render object
    ret.append(car);
    return ret;
}

From source file:com.sangupta.fileanalysis.db.DBResultViewer.java

private static void center(String value, int size) {
    System.out.print("| " + StringUtils.center(value, size) + " ");
}