Example usage for java.util Formatter Formatter

List of usage examples for java.util Formatter Formatter

Introduction

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

Prototype

public Formatter(OutputStream os) 

Source Link

Document

Constructs a new formatter with the specified output stream.

Usage

From source file:com.itemanalysis.psychometrics.mixture.MvNormalComponentDistribution.java

public String printMixingProportion() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    f.format("%6.4f", pi);
    f.format("%n");
    return f.toString();
}

From source file:com.itemanalysis.psychometrics.mixture.MvNormalComponentDistribution.java

public String printMean() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    for (int i = 0; i < mu.getRowDimension(); i++) {
        f.format("% 8.2f", mu.getEntry(i, 0));
        f.format("%5s", "");
    }//from ww w .ja  va  2  s . c  o  m
    f.format("%n");
    return f.toString();
}

From source file:com.tecapro.inventory.common.util.LogUtil.java

/**
 * // w w  w . j  a  v  a 2 s.c om
 * End log output
 * 
 * @param log
 * @param clazz
 * @param method
 * @param time
 */
@SuppressWarnings("resource")
public void endLog(Log log, String clazz, String method, InfoValue info, long time) {

    long totalMemory = Runtime.getRuntime().totalMemory();
    long freeMemory = Runtime.getRuntime().freeMemory();

    Integer level = LOG_LEVEL.get(Thread.currentThread());

    if (level != null) {
        level -= 1;
    } else {
        level = 0;
    }

    if (level == 0) {
        LOG_LEVEL.remove(Thread.currentThread());
    } else {
        LOG_LEVEL.put(Thread.currentThread(), level);
    }

    Formatter formatter = new Formatter(new StringBuffer());
    log.info(returnLogString(clazz, method, info, LogPrefix.END,
            new StringBuffer().append(totalMemory - freeMemory).append(",").append(totalMemory).append(",")
                    .append(formatter.format("%.3f", (System.nanoTime() - time) / 1000000.0D)).append("ms")
                    .toString()));

}

From source file:dk.dma.msinm.user.security.SecurityUtils.java

/**
 * Hex the byte buffer/*from  ww w.  j  av a2 s  . c o m*/
 * @param bytes the bytes to Hex
 * @return the result
 */
public static String hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);

    Formatter formatter = new Formatter(sb);
    for (byte b : bytes) {
        formatter.format("%02x", b);
    }

    return sb.toString();
}

From source file:ca.nines.ise.cmd.Wikify.java

private void wikifyCharacters(PrintStream out) {
    // accented/*  www .j a  v  a  2s .  co  m*/
    try {
        Map<String, String> cm = AccentCharNode.mapping();
        Writer xmlOut = new XMLWriter(out);
        CharNode cn = new AccentCharNode();
        Formatter formatter = new Formatter(out);

        for (String c : cm.keySet()) {
            cn.setText("{" + c + "a}");
            formatter.format("%s %s %s %s%n", c, Character.getName(cm.get(c).charAt(0)), cn.getText(),
                    cn.unicode());
            xmlOut.render(cn.expanded());
            out.println();
        }

    } catch (Exception ex) {
        Logger.getLogger(Wikify.class.getName()).log(Level.SEVERE, null, ex);
    }

    // code point
    // digraph
    // ligature
    // space
    // typographic
    // unicode
    // nested
}

From source file:com.admc.jcreole.Indexer.java

/**
 * This is a highly-modified fork of Tomcat's method
 * DefaultServlet.renderHtml().//from w  ww. j av a 2  s.  co m
 *
 * @param directory  Will throw an IllegalArgumentException if this is not
 *        a real directory.
 * @param listUp  Generate an entry for "..".
 * @return HTML fragment that is a HTML table element.
 */
public StringBuilder generateTable(File directory, String displayName, boolean listUp,
        FileComparator.SortBy sortBy, boolean ascendSort) {
    /*
     * TODO: Use an EnumMap or something to cache FileComparators instead
     * of instantiating one for every method call.
     */
    Matcher matcher = null;
    if (!directory.isDirectory())
        throw new IllegalArgumentException("Not a directory:  " + directory.getAbsolutePath());
    if ((namePattern == null && nameFormatString != null) || (namePattern != null && nameFormatString == null))
        throw new IllegalStateException(
                "'namePattern' and 'nameFormatString' must either both be " + "set or both be null");
    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb);

    String name = displayName;

    sb.append("<table class=\"jcreole_dirindex\" width=\"100%\" "
            + "cellspacing=\"0\" cellpadding=\"5\" align=\"center\">\r\n");

    // Render the column headings
    sb.append("<tr>\r\n");
    sb.append("<td align=\"left\"><font size=\"+1\"><strong>");
    sb.append("<a href=\"?sort=");
    try {
        sb.append(URLEncoder.encode((sortBy == FileComparator.SortBy.NAME && ascendSort) ? "-" : "+", "UTF-8"));
        sb.append("NAME\">Nodename</a>");
        if (sortBy == FileComparator.SortBy.NAME)
            sb.append("<sup>").append(ascendSort ? '+' : '-').append("</sup>");
        sb.append("</strong></font></td>\r\n");
        sb.append("<td align=\"center\"><font size=\"+1\"><strong>");
        sb.append("<a href=\"?sort=");
        sb.append(URLEncoder.encode((sortBy == FileComparator.SortBy.SIZE && ascendSort) ? "-" : "+", "UTF-8"));
        sb.append("SIZE\">Size</a>");
        if (sortBy == FileComparator.SortBy.SIZE)
            sb.append("<sup>").append(ascendSort ? '+' : '-').append("</sup>");
        sb.append("</strong></font></td>\r\n");
        sb.append("<td align=\"right\"><font size=\"+1\"><strong>");
        sb.append("<a href=\"?sort=");
        sb.append(URLEncoder.encode((sortBy == FileComparator.SortBy.MODIFIED && ascendSort) ? "-" : "+",
                "UTF-8"));
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException("Unable to encode to UTF-8");
    }
    sb.append("MODIFIED\">Last Modified</a>");
    if (sortBy == FileComparator.SortBy.MODIFIED)
        sb.append("<sup>").append(ascendSort ? '+' : '-').append("</sup>");
    sb.append("</strong></font></td>\r\n");
    sb.append("</tr>");

    boolean shade = true;

    // DIR ENTRY:
    if (listUp) {
        sb.append("<tr");
        sb.append(" bgcolor=\"#eeeeee\"");
        sb.append(">\r\n");

        sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n");
        sb.append("<a href=\"../\"><tt><strong>..</strong>&nbsp;&nbsp;(");
        sb.append(StringEscapeUtils.escapeHtml(tailStripperPattern.matcher(displayName).replaceFirst("")));
        sb.append(")</tt></a></td>\r\n");

        sb.append("<td align=\"right\"><tt>");
        sb.append("&nbsp;");
        sb.append("</tt></td>\r\n");

        sb.append("<td align=\"right\"><tt>");
        sb.append(StringEscapeUtils
                .escapeHtml(isoDateTimeFormatter.format(directory.getParentFile().lastModified())));
        sb.append("</tt></td>\r\n");

        sb.append("</tr>\r\n");
    } // END DIR ENTRY

    List<File> fileList = Arrays.asList(directory.listFiles(filter));
    Collections.sort(fileList, new FileComparator(sortBy, ascendSort));

    // Render the directory entries within this directory
    for (File file : fileList) {
        String nodeName = file.getName();
        if (namePattern != null) {
            if (file.isFile()) {
                matcher = namePattern.matcher(nodeName);
                if (!matcher.matches())
                    continue;
            } else {
                matcher = null;
            }
        }

        shade = !shade;
        sb.append("<tr");
        if (shade)
            sb.append(" bgcolor=\"#eeeeee\"");
        sb.append(">\r\n");

        sb.append("<td align=\"left\">&nbsp;&nbsp;\r\n");
        sb.append("<a href=\"");
        if (matcher == null) {
            sb.append(nodeName);
        } else {
            // Terrible hack dur to terrible Java varargs limitation:
            switch (matcher.groupCount()) {
            case 1:
                formatter.format(nameFormatString, matcher.group(1));
                break;
            case 2:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2));
                break;
            case 3:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3));
                break;
            case 4:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4));
                break;
            case 5:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5));
                break;
            case 6:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5), matcher.group(6));
                break;
            case 7:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5), matcher.group(6), matcher.group(7));
                break;
            case 8:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5), matcher.group(6), matcher.group(7),
                        matcher.group(8));
                break;
            case 9:
                formatter.format(nameFormatString, matcher.group(1), matcher.group(2), matcher.group(3),
                        matcher.group(4), matcher.group(5), matcher.group(6), matcher.group(7),
                        matcher.group(8), matcher.group(9));
                break;
            default:
                throw new IllegalArgumentException(
                        "Pattern captured too many (" + matcher.groupCount() + ") groups: " + namePattern);
            }
        }
        if (file.isDirectory())
            sb.append('/');
        sb.append("\"><tt>");
        sb.append(StringEscapeUtils.escapeHtml(nodeName));
        if (file.isDirectory())
            sb.append('/');
        sb.append("</tt></a></td>\r\n");

        sb.append("<td align=\"right\"><tt>");
        if (file.isDirectory())
            sb.append("&nbsp;");
        else if (file.isFile())
            sb.append(file.length());
        sb.append("</tt></td>\r\n");

        sb.append("<td align=\"right\"><tt>");
        sb.append(StringEscapeUtils.escapeHtml(isoDateTimeFormatter.format(file.lastModified())));
        sb.append("</tt></td>\r\n");

        sb.append("</tr>\r\n");
    }

    // Render the page footer
    sb.append("</table>\r\n");

    return sb;
}

From source file:com.hazelcast.stabilizer.Utils.java

/**
 * Formats a number and adds padding to the left.
 * It is very inefficient; but a lot easier to deal with the formatting API.
 *
 * @param number    number to format//from ww w  .j  av a2 s  .c  om
 * @param length    width of padding
 * @return formatted number
 */
public static String formatDouble(double number, int length) {
    StringBuffer sb = new StringBuffer();
    Formatter f = new Formatter(sb);
    f.format("%,.2f", number);

    return padLeft(sb.toString(), length);
}

From source file:com.itemanalysis.psychometrics.scaling.NormalizedScore.java

public String printTable(int precision) {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    String f1 = "%10." + precision + "f";
    String f2 = "%10s";
    //      String f3="%10.4f";

    //table header
    f.format("%28s", "SCORE TABLE");
    f.format("%n");
    f.format("%45s", "=============================================");
    f.format("%n");
    f.format(f2, "Original");
    f.format("%5s", "");
    f.format(f2, "Percentile");
    f.format("%5s", "");
    f.format(f2, "Normalized");
    f.format("%n");

    f.format(f2, "Value");
    f.format("%5s", "");
    f.format(f2, "Rank");
    f.format("%5s", "");
    f.format(f2, "Score");
    f.format("%n");
    f.format("%45s", "---------------------------------------------");
    f.format("%n");

    int rs = 0;//from  w w w  . j  a va  2s  . c  o m
    double value = 0.0;
    double pr = 0.0;

    Iterator<Integer> iter = normScoreTable.keySet().iterator();
    while (iter.hasNext()) {
        rs = iter.next();
        pr = prank.getPercentileRankAt(rs);
        value = normScoreTable.get(rs);
        f.format(f1, (double) rs);
        f.format("%5s", "");
        f.format(f1, pr);
        f.format("%5s", "");
        f.format(f1, value);
        f.format("%5s", "");
        f.format("%n");
    }

    f.format("%45s", "=============================================");
    f.format("%n");
    return f.toString();
}

From source file:com.itemanalysis.psychometrics.mixture.MvNormalComponentDistribution.java

public String printCovariance() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);

    for (int i = 0; i < sigma.getRowDimension(); i++) {
        for (int j = 0; j < sigma.getColumnDimension(); j++) {
            f.format("% 8.2f", sigma.getEntry(i, j));
            f.format("%5s", "");
        }/*from  www .  j  a v  a 2  s  .  c om*/
        f.format("%n");
    }
    return f.toString();
}

From source file:org.apache.falcon.ResponseHelper.java

public static String getString(FeedInstanceResult result) {
    StringBuilder sb = new StringBuilder();
    String toAppend;//from   ww  w  .j  a  va 2s. com

    sb.append("Consolidated Status: ").append(result.getStatus()).append("\n");

    sb.append("\nInstances:\n");
    Formatter formatter = new Formatter(sb);
    formatter.format("%-16s%-20s%-16s%-16s%-20s%-16s", "Cluster", "Instance", "Status", "Size", "CreationTime",
            "Details");
    sb.append("\n");
    sb.append(
            "-----------------------------------------------------------------------------------------------\n");
    if (result.getInstances() != null) {
        for (FeedInstanceResult.Instance instance : result.getInstances()) {
            formatter.format("%-16s", instance.getCluster() != null ? instance.getCluster() : "-");
            formatter.format("%-20s", instance.getInstance() != null ? instance.getInstance() : "-");
            formatter.format("%-16s", instance.getStatus() != null ? instance.getStatus() : "-");
            formatter.format("%-16s", instance.getSize() != -1 ? instance.getSizeH() : "-");
            formatter.format("%-20s",
                    instance.getCreationTime() != 0
                            ? SchemaHelper.formatDateUTC(new Date(instance.getCreationTime()))
                            : "-");
            formatter.format("%-16s", StringUtils.isEmpty(instance.getUri()) ? "-" : instance.getUri());
            sb.append("\n");
        }
    }
    sb.append("\nAdditional Information:\n");
    sb.append("Response: ").append(result.getMessage());
    sb.append("Request Id: ").append(result.getRequestId());
    return sb.toString();
}