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.cloudera.sqoop.manager.OracleCompatTest.java

@Override
protected String getBlobInsertStr(String blobData) {
    // Oracle wants blob data encoded as hex (e.g. '01fca3b5').

    StringBuilder sb = new StringBuilder();
    sb.append("'");

    Formatter fmt = new Formatter(sb);
    try {//w ww. jav  a 2 s.c o  m
        for (byte b : blobData.getBytes("UTF-8")) {
            fmt.format("%02X", b);
        }
    } catch (UnsupportedEncodingException uee) {
        // Should not happen; Java always supports UTF-8.
        fail("Could not get utf-8 bytes for blob string");
        return null;
    }
    sb.append("'");
    return sb.toString();
}

From source file:contrail.stages.CompressAndCorrect.java

/**
 * Remove the tips in the graph./*w  w  w . j  a  va  2  s  .c o m*/
 * @param inputPath
 * @param outputPath
 * @return True if any tips were removed.
 */
private JobInfo removeTips(String inputPath, String outputPath) throws Exception {
    RemoveTipsAvro stage = new RemoveTipsAvro();
    stage.setConf(getConf());
    // Make a shallow copy of the stage options required by the compress
    // stage.
    Map<String, Object> stageOptions = ContrailParameters.extractParameters(this.stage_options,
            stage.getParameterDefinitions().values());

    stageOptions.put("inputpath", inputPath);
    stageOptions.put("outputpath", outputPath);
    stage.setParameters(stageOptions);
    RunningJob job = stage.runJob();

    JobInfo result = new JobInfo();
    if (job == null) {
        result.logMessage = "RemoveTips stage was skipped because graph would not change.";
        sLogger.info(result.logMessage);
        result.graphPath = inputPath;
        result.graphChanged = false;
        return result;
    }

    // Check if any tips were found.
    long tipsRemoved = job.getCounters()
            .findCounter(RemoveTipsAvro.NUM_REMOVED.group, RemoveTipsAvro.NUM_REMOVED.tag).getValue();

    if (tipsRemoved > 0) {
        result.graphChanged = true;
    }
    result.graphPath = outputPath;

    Formatter formatter = new Formatter(new StringBuilder());
    result.logMessage = formatter.format("RemoveTips: number of nodes removed %d", tipsRemoved).toString();
    return result;
}

From source file:contrail.stages.CompressAndCorrect.java

/**
 * Remove low coverage nodes.//from ww  w.ja  va2s  .  co  m
 * @param inputPath
 * @param outputPath
 * @return True if any tips were removed.
 */
private JobInfo removeLowCoverageNodes(String inputPath, String outputPath) throws Exception {
    RemoveLowCoverageAvro stage = new RemoveLowCoverageAvro();
    stage.setConf(getConf());
    // Make a shallow copy of the stage options required by the compress
    // stage.
    Map<String, Object> stageOptions = ContrailParameters.extractParameters(this.stage_options,
            stage.getParameterDefinitions().values());

    stageOptions.put("inputpath", inputPath);
    stageOptions.put("outputpath", outputPath);
    stage.setParameters(stageOptions);
    RunningJob job = stage.runJob();

    JobInfo result = new JobInfo();
    if (job == null) {
        result.logMessage = "RemoveLowCoverage stage was skipped because graph would not " + "change.";
        sLogger.info(result.logMessage);
        result.graphPath = inputPath;
        result.graphChanged = false;
        return result;
    }
    // Check if any tips were found.
    long nodesRemoved = job.getCounters()
            .findCounter(RemoveLowCoverageAvro.NUM_REMOVED.group, RemoveLowCoverageAvro.NUM_REMOVED.tag)
            .getValue();

    result.graphPath = outputPath;
    if (nodesRemoved > 0) {
        result.graphChanged = true;
    }

    Formatter formatter = new Formatter(new StringBuilder());
    result.logMessage = formatter.format("RemoveLowCoverage removed %d nodes.", nodesRemoved).toString();
    return result;
}

From source file:cross.datastructures.pipeline.CommandPipeline.java

/**
 * Store the runtime of the last command.
 *
 * @param start    wall clock start time of the command
 *
 * @param stop     wall clock stop time of the command
 * @param cmd      the command// w  w w .j  a va2s.c o  m
 * @param workflow the current workflow
 */
protected void storeCommandRuntime(long start, long stop, final IFragmentCommand cmd,
        final IWorkflow workflow) {
    final float seconds = ((float) stop - start) / ((float) 1000000000);
    final StringBuilder sb = new StringBuilder();
    final Formatter formatter = new Formatter(sb);
    formatter.format(CommandPipeline.NUMBERFORMAT, (seconds));
    log.info("Runtime of command {}: {} sec", cmd.getClass().getSimpleName(), sb.toString());
    Map<String, Object> statsMap = new HashMap<>();
    statsMap.put("RUNTIME_MILLISECONDS", (double) stop - start / 1000000.f);
    statsMap.put("RUNTIME_SECONDS", (double) seconds);
    DefaultWorkflowStatisticsResult dwsr = new DefaultWorkflowStatisticsResult();
    dwsr.setWorkflowElement(cmd);
    dwsr.setWorkflowSlot(WorkflowSlot.STATISTICS);
    dwsr.setStats(statsMap);
    workflow.append(dwsr);
}

From source file:gdv.xport.util.XmlFormatter.java

private void write(final String attribute, final String format, final Object... args)
        throws XMLStreamException {
    Formatter formatter = new Formatter();
    String s = formatter.format(format, args).toString();
    xmlStreamWriter.writeAttribute(attribute, s);
    formatter.close();//from   ww w  .jav a2s  .com
}

From source file:contrail.stages.CompressAndCorrect.java

/**
 * PopBubbles in the graph./* w w  w.j  av  a 2s.  c om*/
 * @param inputPath
 * @param outputPath
 * @return JobInfo
 */
private JobInfo popBubbles(String inputPath, String outputPath) throws Exception {
    FindBubblesAvro findStage = new FindBubblesAvro();
    findStage.setConf(getConf());
    String findOutputPath = new Path(outputPath, "FindBubbles").toString();
    {
        // Make a shallow copy of the stage options required.
        Map<String, Object> stageOptions = ContrailParameters.extractParameters(this.stage_options,
                findStage.getParameterDefinitions().values());

        stageOptions.put("inputpath", inputPath);
        stageOptions.put("outputpath", findOutputPath);
        findStage.setParameters(stageOptions);
    }

    RunningJob findJob = findStage.runJob();

    if (findJob == null) {
        JobInfo result = new JobInfo();
        result.logMessage = "FindBubbles stage was skipped because graph would not change.";
        sLogger.info(result.logMessage);
        result.graphPath = inputPath;
        result.graphChanged = false;
        return result;
    }

    // Check if any bubbles were found.
    long bubblesFound = findJob.getCounters()
            .findCounter(FindBubblesAvro.num_bubbles.group, FindBubblesAvro.num_bubbles.tag).getValue();

    if (bubblesFound == 0) {
        // Since no bubbles were found, we don't need to run the second phase
        // of pop bubbles.
        JobInfo result = new JobInfo();
        result.graphChanged = false;
        // Since the graph didn't change return the input path as the path to
        // the graph.
        result.graphPath = inputPath;
        result.logMessage = "FindBubbles found 0 bubbles.";
        return result;
    }

    PopBubblesAvro popStage = new PopBubblesAvro();
    popStage.setConf(getConf());
    String popOutputPath = new Path(outputPath, "PopBubbles").toString();
    {
        // Make a shallow copy of the stage options required.
        Map<String, Object> stageOptions = ContrailParameters.extractParameters(this.stage_options,
                popStage.getParameterDefinitions().values());

        stageOptions.put("inputpath", findOutputPath);
        stageOptions.put("outputpath", popOutputPath);
        popStage.setParameters(stageOptions);
    }
    RunningJob popJob = popStage.runJob();

    JobInfo result = new JobInfo();
    result.graphChanged = true;
    result.graphPath = popOutputPath;

    Formatter formatter = new Formatter(new StringBuilder());
    result.logMessage = formatter.format("FindBubbles: number of nodes removed %d", bubblesFound).toString();
    return result;
}

From source file:org.LexGrid.LexBIG.example.ScoreTerm.java

/**
 * Display results to the user./*from   w  w w . j  a  v a 2s  .c  om*/
 * 
 * @param result
 */
protected void printReport(BidiMap result) {
    final String Dash6 = "------";
    final String Dash10 = "----------";
    final String Dash60 = "------------------------------------------------------------";

    Formatter f = new Formatter();

    // Print header.
    String format = "%-5.5s|%-10.10s|%-60.60s\n";
    Object[] hSep = new Object[] { Dash6, Dash10, Dash60 };
    f.format(format, hSep);
    f.format(format, new Object[] { "Score", "Code", "Term" });
    f.format(format, hSep);

    // Iterate over the result.
    for (MapIterator items = result.inverseBidiMap().mapIterator(); items.hasNext();) {
        ScoredTerm st = (ScoredTerm) items.next();
        String code = (String) items.getValue();

        // Evaluate code
        if (code != null && code.length() > 10)
            code = code.substring(0, 7) + "...";

        // Evaluate term (wrap if necessary)
        String term = st.term;
        if (term != null && term.length() < 60)
            f.format(format, new Object[] { st.score, code, term });
        else {
            String sub = term.substring(0, 60);
            f.format(format, new Object[] { st.score, code, sub });
            int begin = 60;
            int end = term.length();
            while (begin < end) {
                sub = term.substring(begin, Math.min(begin + 60, end));
                f.format(format, new Object[] { "", "", sub });
                begin += 60;
            }
        }
    }
    Util.displayMessage(f.out().toString());
}

From source file:com.itemanalysis.psychometrics.cfa.AbstractConfirmatoryFactorAnalysisEstimator.java

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    double[] fl = model.getFactorLoading();
    double[] er = model.getErrorVariance();

    for (int i = 0; i < nItems; i++) {
        f.format("% .4f", fl[i]);
        f.format("%5s", "");
        f.format("% .4f", er[i]);
        f.format("%n");
    }/*from  w ww  .jav  a 2 s .  c o m*/

    f.format("%10s", "McDonald's Omega = ");
    f.format("%8.4f", mcdonaldOmega());
    f.format("%n");
    f.format("%10s", "GFI = ");
    f.format("%8.4f", gfi());
    f.format("%n");
    f.format("%10s", "AGFI = ");
    f.format("%8.4f", agfi());
    f.format("%n");
    f.format("%10s", "RMSEA = ");
    f.format("%8.4f", rmsea());
    f.format("%n");
    f.format("%10s", "RMSR = ");
    f.format("%8.4f", Math.sqrt(meanSquaredResidual()));
    f.format("%n");
    f.format("%10s", "BIC = ");
    f.format("%8.4f", Math.sqrt(bic()));
    f.format("%n");
    f.format("%10s", "X^2 = ");
    f.format("%8.4f", chisquare());
    f.format("%n");
    f.format("%10s", "df = ");
    f.format("%8.4f", degreesOfFreedom());
    f.format("%n");
    f.format("%10s", "p = ");
    f.format("%8.4f", pvalue());
    f.format("%n");
    return f.toString();
}

From source file:org.ocpsoft.rewrite.servlet.config.proxy.ProxyServlet.java

/**
 * Encodes characters in the query or fragment part of the URI.
 * /*  w w  w .ja  v a2  s.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. TODO:
     * replace/compare to with Rewrite Encoding
     */
    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(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.itemanalysis.psychometrics.polycor.PolychoricLogLikelihoodML.java

public String print(double[] x) {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    int am1 = alpha.length - 1;
    int bm1 = beta.length - 1;

    f.format("%34s", "Polychoric correlation, ML est. = ");
    f.format("%6.4f", rho);
    f.format(" (%6.4f)", Math.sqrt(variance[0][0]));
    f.format("%n");
    f.format("%41s", "Test of bivariate normality: Chisquare = ");
    f.format("%-8.4f", chiSquare);
    f.format("%6s", " df = ");
    f.format("%-6.0f", df);
    f.format("%5s", " p = ");
    f.format("%-6.4f", probChiSquare);
    f.format("%n");
    f.format("%n");
    f.format("%18s", "Row Thresholds");
    f.format("%n");
    f.format("%-15s", "Threshold");
    f.format("%-10s", "Std.Err.");
    f.format("%n");

    for (int i = 0; i < am1; i++) {
        f.format("%6.4f", x[i + 1]);
        f.format("%9s", "");
        f.format("%6.4f", Math.sqrt(variance[i + 1][i + 1]));
        f.format("%n");
    }/*w  w  w.  j  av  a  2  s .  co  m*/

    f.format("%n");
    f.format("%n");
    f.format("%19s", "Column Thresholds");
    f.format("%n");
    f.format("%-15s", "Threshold");
    f.format("%-10s", "Std.Err.");
    f.format("%n");

    for (int i = 0; i < bm1; i++) {
        f.format("% 6.4f", x[i + 1 + am1]);
        f.format("%9s", "");
        f.format("% 6.4f", Math.sqrt(variance[i + 1 + am1][i + 1 + am1]));
        f.format("%n");
    }

    f.format("%n");
    return f.toString();

}