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.itemanalysis.psychometrics.mixture.MvNormalMixtureModel.java

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

    f.format("%20s", "Number of groups = ");
    f.format("%-4d", groups);
    f.format("%n");
    f.format("%20s", "Free parameters = ");
    f.format("%-4d", freeParameters());
    f.format("%n");
    f.format("%20s", "Sample size = ");
    f.format("%-10d", sampleSize);
    f.format("%n");
    f.format("%20s", "Log-likelihood = ");
    f.format("%-12.4f", this.loglikelihood());
    f.format("%n");
    f.format("%20s", "Converged = ");
    f.format("%-5s", converged);
    f.format("%n");
    f.format("%20s", "Status = ");
    f.format("%-35s", statusMessage);
    f.format("%n");
    f.format("%n");
    f.format(fit.printFitStatistics());//from   w  ww.  j  av  a2s.c om
    f.format("%n");

    MvNormalComponentDistribution mvnDist = null;
    for (int g = 0; g < groups; g++) {
        f.format("%n");
        mvnDist = (MvNormalComponentDistribution) compDistribution[g];
        f.format("%-12s", "Group " + (g + 1) + " ");
        f.format("%n");
        f.format("%12s", "Mix Prop: ");
        f.format(mvnDist.printMixingProportion());
        f.format("%12s", "Mean: ");
        f.format(mvnDist.printMean());
        f.format("%12s", "Covar: ");
        f.format("%n");
        f.format(mvnDist.printCovariance());
    }
    return f.toString();
}

From source file:de.huxhorn.sulky.blobs.impl.BlobRepositoryImpl.java

private String copyAndHash(InputStream input, File into) throws IOException {
    MessageDigest digest = createMessageDigest();

    DigestInputStream dis = new DigestInputStream(input, digest);
    IOException ex;/*from  w  w w.j  a  v  a 2  s  . c o  m*/
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(into);
        IOUtils.copyLarge(dis, fos);
        byte[] hash = digest.digest();
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    } catch (IOException e) {
        ex = e;
    } finally {
        IOUtils.closeQuietly(dis);
        IOUtils.closeQuietly(fos);
    }
    if (logger.isWarnEnabled())
        logger.warn("Couldn't retrieve data from input!", ex);
    deleteTempFile(into);
    throw ex;
}

From source file:de.huxhorn.sulky.blobs.impl.BlobRepositoryImpl.java

private boolean valid(String id, File file) {
    if (!validating) {
        return true;
    }/*ww  w. j a  va 2  s  .  c  o  m*/
    MessageDigest digest = createMessageDigest();

    FileInputStream input = null;
    try {
        input = new FileInputStream(file);
        DigestInputStream dis = new DigestInputStream(input, digest);
        for (;;) {
            if (dis.read() < 0) {
                break;
            }
        }
        byte[] hash = digest.digest();
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString().equals(id);
    } catch (IOException e) {
        // ignore...
    } finally {
        IOUtils.closeQuietly(input);
    }
    return false;
}

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

/**
 * Generate the body of the refresh function
 */// w w w. java 2  s.  c  o  m
public static void generateRefreshBody(final Writer writer, final ServletContext application)
        throws ParseException, IOException {
    if (LOG.isTraceEnabled()) {
        LOG.trace("Entering generateRefreshBody");
    }

    final ChallengeDescription description = ApplicationAttributes.getChallengeDescription(application);
    final Formatter formatter = new Formatter(writer);

    final PerformanceScoreCategory performanceElement = description.getPerformance();

    // output the assignments of each element
    for (final AbstractGoal agoal : performanceElement.getGoals()) {
        if (agoal.isComputed()) {
            // output calls to the computed goal methods

            final String goalName = agoal.getName();
            final String computedVarName = getVarNameForComputedScore(goalName);
            formatter.format("%s();%n", getComputedMethodName(goalName));

            // add to the total score
            formatter.format("score += %s;%n", computedVarName);

            formatter.format("%n");

        } else {
            final Goal goal = (Goal) agoal;
            final String name = goal.getName();
            final double multiplier = goal.getMultiplier();
            final double min = goal.getMin();
            final double max = goal.getMax();
            final String rawVarName = getVarNameForRawScore(name);
            final String computedVarName = getVarNameForComputedScore(name);

            if (LOG.isTraceEnabled()) {
                LOG.trace("name: " + name);
                LOG.trace("multiplier: " + multiplier);
                LOG.trace("min: " + min);
                LOG.trace("max: " + max);
            }

            formatter.format("<!-- %s -->%n", name);

            if (goal.isEnumerated()) {
                // enumerated
                final List<EnumeratedValue> posValues = agoal.getSortedValues();
                for (int valueIdx = 0; valueIdx < posValues.size(); valueIdx++) {
                    final EnumeratedValue valueEle = posValues.get(valueIdx);

                    final String value = valueEle.getValue();
                    final double valueScore = valueEle.getScore();
                    if (valueIdx > 0) {
                        formatter.format("} else ");
                    }

                    formatter.format("if(%s == \"%s\") {%n", rawVarName, value);
                    formatter.format("  document.scoreEntry.%s[%d].checked = true;%n", name, valueIdx);
                    formatter.format("  %s = %f * %s;%n", computedVarName, valueScore, multiplier);

                    formatter.format("  document.scoreEntry.%s.value = '%s'%n",
                            getElementNameForYesNoDisplay(name), value.toUpperCase());
                } // foreach value
                formatter.format("}%n");
            } else if (goal.isYesNo()) {
                // set the radio button to match the gbl variable
                formatter.format("if(%s == 0) {%n", rawVarName);
                // 0/1 needs to match the order of the buttons generated in
                // generateYesNoButtons
                formatter.format("  document.scoreEntry.%s[0].checked = true%n", name);
                formatter.format("  document.scoreEntry.%s_radioValue.value = 'NO'%n", name);
                formatter.format("} else {%n");
                formatter.format("  document.scoreEntry.%s[1].checked = true%n", name);
                formatter.format("  document.scoreEntry.%s_radioValue.value = 'YES'%n", name);
                formatter.format("}%n");
                formatter.format("%s = %s * %s;%n", computedVarName, rawVarName, multiplier);
            } else {
                // set the count form element
                formatter.format("document.scoreEntry.%s.value = %s;%n", name, rawVarName);
                formatter.format("%s = %s * %s;%n", computedVarName, rawVarName, multiplier);
            }

            // add to the total score
            formatter.format("score += %s;%n", computedVarName);

            // set the score form element
            formatter.format("document.scoreEntry.score_%s.value = %s;%n", name, computedVarName);
            formatter.format("%n");
        }
    } // end foreach goal

    // set the radio buttons for score verification
    formatter.format("if(Verified == 0) {%n");
    // order of elements needs to match generateYesNoButtons
    formatter.format("  document.scoreEntry.Verified[0].checked = true%n"); // NO
    formatter.format("} else {%n");
    formatter.format("  document.scoreEntry.Verified[1].checked = true%n"); // YES
    formatter.format("}%n");

    if (LOG.isTraceEnabled()) {
        LOG.trace("Exiting generateRefreshBody");
    }

}

From source file:com.fuseim.webapp.ProxyServlet.java

/**
 * Encodes characters in the query or fragment part of the URI.
 *
 * <p>Unfortunately, an incoming URI sometimes has characters disallowed by the spec. HttpClient
 * insists that the outgoing proxied request has a valid URI because it uses Java's {@link URI}.
 * To be more forgiving, we must escape the problematic characters. See the URI class for the
 * spec./*from w  ww.j  a v  a 2  s .  c om*/
 *
 * @param in example: name=value&amp;foo=bar#fragment
 */
protected static CharSequence encodeUriQuery(CharSequence in) {
    //Note that I can't simply use URI.java to encode because it will escape pre-existing escaped things.
    StringBuilder outBuf = null;
    Formatter formatter = null;
    for (int i = 0; i < in.length(); i++) {
        char c = in.charAt(i);
        boolean escape = true;
        if (c < 128) {
            if (asciiQueryChars.get((int) c)) {
                escape = false;
            }
        } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) { //not-ascii
            escape = false;
        }
        if (!escape) {
            if (outBuf != null)
                outBuf.append(c);
        } else {
            //escape
            if (outBuf == null) {
                outBuf = new StringBuilder(in.length() + 5 * 3);
                outBuf.append(in, 0, i);
                formatter = new Formatter(outBuf);
            }
            //leading %, 0 padded, width 2, capital hex
            formatter.format("%%%02X", (int) c); //TODO
        }
    }
    return outBuf != null ? outBuf : in;
}

From source file:io.hops.hopsworks.api.kibana.ProxyServlet.java

/**
 * Encodes characters in the query or fragment part of the URI.
 * <p>/*  w w  w.ja v  a 2s.com*/
 * <p>
 * Unfortunately, an incoming URI sometimes has characters disallowed by the
 * spec. HttpClient
 * insists that the outgoing proxied request has a valid URI because it uses
 * Java's {@link URI}.
 * To be more forgiving, we must escape the problematic characters. See the
 * URI class for the
 * spec.
 *
 * @param in example: name=value&foo=bar#fragment
 */
protected static CharSequence encodeUriQuery(CharSequence in) {
    //Note that I can't simply use URI.java to encode because it will escape 
    //pre-existing escaped things.
    StringBuilder outBuf = null;
    Formatter formatter = null;
    for (int i = 0; i < in.length(); i++) {
        char c = in.charAt(i);
        boolean escape = true;
        if (c < 128) {
            if (asciiQueryChars.get((int) c)) {
                escape = false;
            }
        } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {//not-ascii
            escape = false;
        }
        if (!escape) {
            if (outBuf != null) {
                outBuf.append(c);
            }
        } else {
            //escape
            if (outBuf == null) {
                outBuf = new StringBuilder(in.length() + 5 * 3);
                outBuf.append(in, 0, i);
                formatter = new Formatter(outBuf);
            }
            //leading %, 0 padded, width 2, capital hex
            formatter.format("%%%02X", (int) c);//TODO
        }
    }
    return outBuf != null ? outBuf : in;
}

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

/**
 * //from   ww  w. j  a  v a 2s.  com
 * 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:com.itemanalysis.psychometrics.cmh.CochranMantelHaenszel.java

public String printHeader() {
    StringBuilder buffer = new StringBuilder();
    Formatter f = new Formatter(buffer);
    f.format("%-10s", " Item");
    f.format("%2s", " ");
    f.format("%10s", "Chi-square");
    f.format("%2s", " ");
    f.format("%7s", "p-value");
    f.format("%2s", " ");
    f.format("%7s", "Valid N");
    f.format("%2s", " ");
    f.format("%28s", "    E.S. (95% C.I.)     ");
    f.format("%2s", " ");
    f.format("%5s", "Class");
    f.format("%2s", " ");
    f.format("%n");
    f.format("%-10s", "----------");
    f.format("%2s", " ");
    f.format("%10s", "----------");
    f.format("%2s", " ");
    f.format("%7s", "-------");
    f.format("%2s", " ");
    f.format("%7s", "-------");
    f.format("%2s", " ");
    f.format("%28s", "----------------------------");
    f.format("%2s", " ");
    f.format("%5s", "-----");
    f.format("%2s", " ");
    f.format("%n");
    return f.toString();
}

From source file:com.google.gwt.jolokia.server.servlet.ProxyServlet.java

/**
 * Encodes characters in the query or fragment part of the URI.
 *
 * <p>/* ww  w  .  j a  va 2s  . c o  m*/
 * Unfortunately, an incoming URI sometimes has characters disallowed by the
 * spec. HttpClient insists that the outgoing proxied request has a valid
 * URI because it uses Java's {@link URI}. To be more forgiving, we must
 * escape the problematic characters. See the URI class for the spec.
 *
 * @param in
 *            example: name=value&foo=bar#fragment
 */
protected static CharSequence encodeUriQuery(CharSequence in) {
    // Note that I can't simply use URI.java to encode because it will
    // escape pre-existing escaped things.
    StringBuilder outBuf = null;
    Formatter formatter = null;
    for (int i = 0; i < in.length(); i++) {
        char c = in.charAt(i);
        boolean escape = true;
        if (c < 128) {
            if (asciiQueryChars.get((int) c)) {
                escape = false;
            }
        } else if (!Character.isISOControl(c) && !Character.isSpaceChar(c)) {// not-ascii
            escape = false;
        }
        if (!escape) {
            if (outBuf != null)
                outBuf.append(c);
        } else {
            // escape
            if (outBuf == null) {
                outBuf = new StringBuilder(in.length() + 5 * 3);
                outBuf.append(in, 0, i);
                formatter = new Formatter(outBuf);
            }
            // leading %, 0 padded, width 2, capital hex
            formatter.format("%%%02X", (int) c);// TODO
        }
    }
    return outBuf != null ? outBuf : in;
}

From source file:edu.uga.cs.fluxbuster.features.FeatureCalculator.java

/**
 * Retrieves the number of dns queries per domain for each cluster
 * generated on a specific run date.//from w ww.  j a  va  2  s .c  o  m
 *
 * @param log_date the run date
 * @return a table of values where the keys are cluster ids and the values 
 *       are the queries per domain value
 * @throws SQLException if there is an error retrieving the queries
 *       per domain values
 */
private Hashtable<Integer, Double> getQueriesPerDomain(Date log_date) throws SQLException {
    Hashtable<Integer, Double> retval = new Hashtable<Integer, Double>();
    StringBuffer querybuf = new StringBuffer();
    Formatter formatter = new Formatter(querybuf);
    formatter.format(properties.getProperty(PREVCLUSTER_QUERY3KEY), df.format(log_date));
    ResultSet rs = null;
    try {
        rs = dbi.executeQueryWithResult(querybuf.toString());
        while (rs.next()) {
            retval.put(rs.getInt(1), rs.getDouble(2));
        }
    } catch (Exception e) {
        if (log.isErrorEnabled()) {
            log.error(e);
        }
    } finally {
        if (rs != null && !rs.isClosed()) {
            rs.close();
        }
        formatter.close();
    }
    return retval;
}