Example usage for java.util Formatter format

List of usage examples for java.util Formatter format

Introduction

In this page you can find the example usage for java.util Formatter format.

Prototype

public Formatter format(String format, Object... args) 

Source Link

Document

Writes a formatted string to this object's destination using the specified format string and arguments.

Usage

From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java

/**
 * Returns a "short" version of the given file size using the appropriate
 * multiplier, and/*from w  ww  . j  av  a  2  s .  co  m*/
 * formatted with a fixed number (see the format) of decimal places. <br/>
 * Examples: 1024 bytes => 1.00 KB, 7 614 525 bytes => 7.26 MB
 * 
 * @param transferred
 * @param unit
 * @return
 */
private static String getFileSizeShortReadable(long transferred, char unit) {
    float res = transferred;
    String unitStr = "B";
    switch (unit) {
    case 'k':
    case 'K':
        res = (float) transferred / (float) (1024);
        unitStr = "KB";
        break;
    case 'm':
    case 'M':
        res = (float) transferred / (float) (1024 * 1024);
        unitStr = "MB";
        break;
    case 'g':
    case 'G':
        res = (float) transferred / (float) (1024 * 1024 * 1024);
        unitStr = "GB";
        break;
    }
    Formatter formatter = new Formatter();
    return formatter.format("%,.2f", res) + " " + unitStr;
}

From source file:fll.web.scoreEntry.ScoreEntry.java

/**
 * Generate the score entry form./* w  w w . jav a  2 s.co  m*/
 */
public static void generateScoreEntry(final JspWriter writer, final ServletContext application)
        throws IOException {
    final ChallengeDescription description = ApplicationAttributes.getChallengeDescription(application);
    final Formatter formatter = new Formatter(writer);

    String prevCategory = null;
    final PerformanceScoreCategory performanceElement = description.getPerformance();
    for (final AbstractGoal goalEle : performanceElement.getGoals()) {
        final String name = goalEle.getName();
        final String title = goalEle.getTitle();
        final String category = goalEle.getCategory();

        try {

            if (!StringUtils.equals(prevCategory, category)) {
                writer.println("<tr><td colspan='5'>&nbsp;</td></tr>");
                if (!StringUtils.isEmpty(category)) {
                    writer.println("<tr><td colspan='5' class='center'><b>" + category + "</b></td></tr>");
                }
            }

            writer.println("<!-- " + name + " -->");
            writer.println("<tr>");
            writer.println("  <td>");
            writer.println("    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font size='3'><b>" + title + ":</b></font>");
            writer.println("  </td>");

            if (goalEle.isComputed()) {
                writer.println("  <td colspan='2' align='center'><b>Computed Goal</b></td>");
            } else {
                if (goalEle.isEnumerated()) {
                    // enumerated
                    writer.println("  <td>");
                    generateEnumeratedGoalButtons(goalEle, name, writer);
                    writer.println("  </td>");
                } else {
                    writer.println("  <td>");
                    generateSimpleGoalButtons(goalEle, name, writer);
                    writer.println("  </td>");
                } // end simple goal
            } // goal

            // computed score
            writer.println("  <td align='right'>");
            writer.println("    <input type='text' name='score_" + name
                    + "' size='3' align='right' readonly tabindex='-1'>");
            writer.println("  </td>");

            // error message
            formatter.format("  <td class='error score-error' id='error_%s'>&nbsp;</td>%n", name);

            writer.println("</tr>");
            writer.println("<!-- end " + name + " -->");
            writer.newLine();
        } catch (final ParseException pe) {
            throw new RuntimeException("FATAL: min/max not parsable for goal: " + name);
        }

        prevCategory = category;
    } // end foreach child of performance
}

From source file:org.smilec.smile.student.CourseList.java

private String createwinnerhtml() {
    String return_html = "";

    String header1 = "<html><head></head><body><P></P><font face=\"helvetica\">";
    String header2 = "<center><Strong>" + getString(R.string.winner_title) + "</Strong></center><br>";
    String body1 = "<P></P>*** " + getString(R.string.quiz_score) + " ***<br>";
    String body2 = getString(R.string.h_score) + ":" + high_score + "<br>";
    String body3 = getString(R.string.name) + ":<br>";
    String mid_html = "";
    for (int i = 0; i < score_winner_name.size(); i++) {
        String name = score_winner_name.get(i);
        mid_html = mid_html + name + "<br>";
    }//from w ww  . j  av  a  2 s  .co  m

    String body4 = "<P></P>";
    String body5 = "*** " + getString(R.string.rating_score_title) + " ***<br>";
    Formatter f = new Formatter();
    String avg = f.format(new String("%4.2f"), high_rating).toString();
    String body6 = getString(R.string.h_avg_rating) + " :" + avg + "<br>";
    String body7 = getString(R.string.name) + " :<br>";
    String next_html = "";
    for (int i = 0; i < rating_winner_name.size(); i++) {
        String r_name = rating_winner_name.get(i);
        next_html = next_html + r_name + "<br>";

    }
    String end = "</font></body></html>";

    return_html = header1 + getHTMLTagForUTF8() + header2 + body1 + body2 + body3 + mid_html + body4 + body5
            + body6 + body7 + next_html + end;

    return return_html;
}

From source file:com.flexoodb.common.FlexUtils.java

/**
* computes the SHA1 hashcode for the passed byte array.
*
* @param  ba byte array./*  w  w w.j  a  v a2 s  . com*/
* @return SHA1 string.
*/
public static String computeSHA1(byte[] ba) {
    String hash = null;
    try {

        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        InputStream is = new ByteArrayInputStream(ba);
        BufferedInputStream bis = new BufferedInputStream(is);

        DigestInputStream dis = new DigestInputStream(bis, sha1);

        while (dis.read() != -1) {
        }
        ;

        byte[] h = sha1.digest();

        Formatter formatter = new Formatter();

        for (byte b : h) {
            formatter.format("%02x", b);
        }

        hash = formatter.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return hash;
}

From source file:com.bluexml.xforms.controller.alfresco.AlfrescoController.java

public String getNodeContentInfo(AlfrescoTransaction transaction, String nodeId) {
    if (StringUtils.trimToNull(nodeId) == null) {
        return "";
    }/*  ww w  .j  a  v a  2s. co  m*/
    String request;
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("nodeId", nodeId);

    try {
        request = requestString(transaction, parameters, MsgId.INT_WEBSCRIPT_OPCODE_NODE_INFO);
    } catch (ServletException e) {
        e.printStackTrace();
        return null;
    }

    if (StringUtils.trimToNull(request) == null) {
        return "";
    }

    String result;
    String[] infos = request.split(","); // <- see the webscript for the actual format
    String nodeName = infos[0]; // the node name
    long size = Long.parseLong(infos[1]); // the content's size
    if (size > 0) {
        String sizeUnit = "";
        Formatter formatter = new Formatter();
        String sizeBytes = formatter.format("%,d", size).toString();
        char multiplier = getFileSizeUnit(size);
        if (multiplier != 'b') {
            sizeUnit = " (" + getFileSizeShortReadable(size, multiplier) + ")";
        } else {
            //
        }
        result = MsgPool.getMsg(MsgId.MSG_UPLOAD_CONTENT_REPO_FORMAT, nodeName, sizeBytes, sizeUnit, nodeId);
    } else {
        result = MsgPool.getMsg(MsgId.MSG_UPLOAD_CONTENT_NO_CONTENT);
    }
    // result += " " + result;
    return result;
}

From source file:com.zimbra.cs.util.ProxyConfOverride.java

public String formatString(Object o) {
    Formatter f = new Formatter();
    f.format("%s", o);
    return f.toString();
}

From source file:com.zimbra.cs.util.ProxyConfOverride.java

public String formatTime(Object o) {
    Formatter f = new Formatter();
    f.format("%dms", (Long) o);
    return f.toString();
}

From source file:com.zimbra.cs.util.ProxyConfOverride.java

public String formatInteger(Object o) {
    Formatter f = new Formatter();
    f.format("%d", (Integer) o);
    return f.toString();
}

From source file:com.zimbra.cs.util.ProxyConfOverride.java

public String formatLong(Object o) {
    Formatter f = new Formatter();
    Long l = (Long) o;/*ww  w.  ja v  a2  s  .c  o  m*/

    if (l % (1024 * 1024) == 0)
        f.format("%dm", l / (1024 * 1024));
    else if (l % 1024 == 0)
        f.format("%dk", l / 1024);
    else
        f.format("%d", l);
    return f.toString();
}

From source file:fr.inrialpes.exmo.align.cli.GroupEval.java

public void printLATEX(Vector<Vector<Object>> result, PrintStream writer) {
    // variables for computing iterative harmonic means
    int expected = 0; // expected so far
    int foundVect[]; // found so far
    int correctVect[]; // correct so far
    long timeVect[]; // time so far
    Formatter formatter = new Formatter(writer);

    fsize = format.length();//  www.j  ava2s.c om
    // JE: the h-means computation should be put out as well
    // Print the header
    writer.println("\\documentclass[11pt]{book}");
    writer.println();
    writer.println("\\begin{document}");
    writer.println("\\date{today}");
    writer.println("");
    writer.println("\n%% Plot generated by GroupEval of alignapi");
    writer.println("\\setlength{\\tabcolsep}{3pt} % May be changed");
    writer.println("\\begin{table}");
    writer.print("\\begin{tabular}{|l||");
    for (int i = size; i > 0; i--) {
        for (int j = fsize; j > 0; j--)
            writer.print("c");
        writer.print("|");
    }
    writer.println("}");
    writer.println("\\hline");
    // For each file do a
    writer.print("algo");
    // for each algo <td spancol='2'>name</td>
    for (String m : listAlgo) {
        writer.print(" & \\multicolumn{" + fsize + "}{c|}{" + m + "}");
    }
    writer.println(" \\\\ \\hline");
    writer.print("test");
    // for each algo <td>Prec.</td><td>Rec.</td>
    for (String m : listAlgo) {
        for (int i = 0; i < fsize; i++) {
            writer.print(" & ");
            if (format.charAt(i) == 'p') {
                writer.print("Prec.");
            } else if (format.charAt(i) == 'f') {
                writer.print("FMeas.");
            } else if (format.charAt(i) == 'o') {
                writer.print("Over.");
            } else if (format.charAt(i) == 't') {
                writer.print("Time");
            } else if (format.charAt(i) == 'r') {
                writer.print("Rec.");
            }
        }
    }
    writer.println(" \\\\ \\hline");
    foundVect = new int[size];
    correctVect = new int[size];
    timeVect = new long[size];
    for (int k = size - 1; k >= 0; k--) {
        foundVect[k] = 0;
        correctVect[k] = 0;
        timeVect[k] = 0;
    }
    for (Vector<Object> test : result) {
        int nexpected = -1;
        // Print the directory 
        writer.print((String) test.get(0));
        // For each record print the values
        Enumeration<Object> f = test.elements();
        f.nextElement();
        for (int k = 0; f.hasMoreElements(); k++) {
            PRecEvaluator eval = (PRecEvaluator) f.nextElement();
            if (eval != null) {
                // iterative H-means computation
                if (nexpected == -1) {
                    expected += eval.getExpected();
                    nexpected = 0;
                }
                foundVect[k] += eval.getFound();
                correctVect[k] += eval.getCorrect();
                timeVect[k] += eval.getTime();

                for (int i = 0; i < fsize; i++) {
                    writer.print(" & ");
                    if (format.charAt(i) == 'p') {
                        formatter.format("%1.2f", eval.getPrecision());
                    } else if (format.charAt(i) == 'f') {
                        formatter.format("%1.2f", eval.getFmeasure());
                    } else if (format.charAt(i) == 'o') {
                        formatter.format("%1.2f", eval.getOverall());
                    } else if (format.charAt(i) == 't') {
                        if (eval.getTime() == 0) {
                            writer.print("-");
                        } else {
                            formatter.format("%1.2f", eval.getTime());
                        }
                    } else if (format.charAt(i) == 'r') {
                        formatter.format("%1.2f", eval.getRecall());
                    }
                }
            } else {
                writer.print(" & \\multicolumn{" + fsize + "}{c|}{n/a}");
            }
        }
        writer.println(" \\\\");
    }
    writer.print("H-mean");
    // Here we are computing a sheer average.
    // While in the column results we print NaN when the returned
    // alignment is empty,
    // here we use the real values, i.e., add 0 to both correctVect and
    // foundVect, so this is OK for computing the average.
    int k = 0;
    // ???
    for (String m : listAlgo) {
        double precision = (double) correctVect[k] / foundVect[k];
        double recall = (double) correctVect[k] / expected;
        for (int i = 0; i < fsize; i++) {
            writer.print(" & ");
            if (format.charAt(i) == 'p') {
                formatter.format("%1.2f", precision);
            } else if (format.charAt(i) == 'f') {
                formatter.format("%1.2f", 2 * precision * recall / (precision + recall));
            } else if (format.charAt(i) == 'o') {
                formatter.format("%1.2f", recall * (2 - (1 / precision)));
            } else if (format.charAt(i) == 't') {
                if (timeVect[k] == 0) {
                    writer.print("-");
                } else {
                    formatter.format("%1.2f", timeVect[k]);
                }
            } else if (format.charAt(i) == 'r') {
                formatter.format("%1.2f", recall);
            }
        }
        ;
        k++;
    }
    writer.println(" \\\\ \\hline");
    writer.println("\\end{tabular}");
    writer.println(
            "\\caption{Plot generated by GroupEval of alignapi \\protect\\footnote{n/a: result alignment not provided or not readable -- NaN: division per zero, likely due to empty alignment.}}");
    writer.println("\\end{table}");
    writer.println("\\end{document}");
}