java.util.Formatter

Here are the examples of the java api class java.util.Formatter taken from open source projects.

1. ConversionBasic#main()

Project: checker-framework
File: ConversionBasic.java
public static void main(String... p) {
    Formatter f = new Formatter();
    // test GENERAL, there is nothing we can do wrong
    @Format({ ConversionCategory.GENERAL }) String s = "%s";
    f.format("Suc-%s-ful", "cess");
    f.format("%b", 4);
    f.format("%B", 7.5);
    f.format("%h", new Date());
    f.format("%H", new Integer(4));
    f.format("%s", new ArrayList<Integer>());
    // test CHAR
    @Format({ ConversionCategory.CHAR }) String c = "%c";
    f.format("%c", 'c');
    f.format("%c", (byte) 67);
    f.format("%c", (int) 67);
    f.format("%c", new Character('c'));
    f.format("%c", new Byte((byte) 67));
    f.format("%c", new Short((short) 67));
    f.format("%C", new Integer(67));
    //:: error: (argument.type.incompatible)
    f.format("%c", 7.5);
    //:: error: (argument.type.incompatible)
    f.format("%C", "Value");
    // test INT
    @Format({ ConversionCategory.INT }) String i = "%d";
    f.format("%d", (byte) 67);
    f.format("%o", (short) 67);
    f.format("%x", (int) 67);
    f.format("%X", (long) 67);
    f.format("%d", new Long(67));
    f.format("%d", BigInteger.ONE);
    //:: error: (argument.type.incompatible)
    f.format("%d", 'c');
    //:: error: (argument.type.incompatible)
    f.format("%d", BigDecimal.ONE);
    // test FLOAT
    @Format({ ConversionCategory.FLOAT }) String d = "%f";
    f.format("%e", (float) 67.1);
    f.format("%E", (double) 67.3);
    f.format("%f", new Float(42.5));
    f.format("%g", new Double(42.5));
    f.format("%G", 67.87);
    f.format("%a", BigDecimal.ONE);
    //:: error: (argument.type.incompatible)
    f.format("%A", 1325);
    //:: error: (argument.type.incompatible)
    f.format("%a", BigInteger.ONE);
    // test TIME
    @Format({ ConversionCategory.TIME }) String t = "%tT";
    f.format("%tD", new Date());
    f.format("%TM", (long) 32165456);
    f.format("%TD", Calendar.getInstance());
    //:: error: (argument.type.incompatible)
    f.format("%tD", 1321543512);
    //:: error: (argument.type.incompatible)
    f.format("%tD", new Object());
    System.out.println(f.toString());
    f.close();
}

2. Main#print()

Project: bnd
File: Main.java
private void print(CommandData command) throws Exception {
    Justif j = new Justif(width, tabs);
    Formatter f = j.formatter();
    f.format("%n[%s]%n", command.name);
    f.format("%s\n\n", Strings.display(command.description, command.title));
    f.format("SHA-1\t1%s%n", Hex.toHexString(command.sha));
    f.format("Bundle Symbolic Name\t1%s%n", Strings.display(command.bsn, "<no bsn>"));
    f.format("Version\t1%s%n", Strings.display(command.version, "<no version>"));
    f.format("JVMArgs\t1%s%n", "JVM Args", command.jvmArgs);
    f.format("Main class\t1%s%n", command.main);
    f.format("Install time\t1%s%n", new Date(command.time));
    f.format("Path\t1%s%n", command.bin);
    f.format("Installed\t1%s%n", command.installed);
    f.format("JRE\t1%s%n", Strings.display(command.java, "<default>"));
    f.format("Trace\t1%s%n", command.trace ? "On" : "Off");
    list(f, "Dependencies", jpm.toString(command.dependencies));
    list(f, "Runbundles", jpm.toString(command.runbundles));
    out.append(j.wrap());
}

3. ZipFileAttributes#toString()

Project: jdk7u-jdk
File: ZipFileAttributes.java
public String toString() {
    StringBuilder sb = new StringBuilder(1024);
    Formatter fm = new Formatter(sb);
    if (creationTime() != null)
        fm.format("    creationTime    : %tc%n", creationTime().toMillis());
    else
        fm.format("    creationTime    : null%n");
    if (lastAccessTime() != null)
        fm.format("    lastAccessTime  : %tc%n", lastAccessTime().toMillis());
    else
        fm.format("    lastAccessTime  : null%n");
    fm.format("    lastModifiedTime: %tc%n", lastModifiedTime().toMillis());
    fm.format("    isRegularFile   : %b%n", isRegularFile());
    fm.format("    isDirectory     : %b%n", isDirectory());
    fm.format("    isSymbolicLink  : %b%n", isSymbolicLink());
    fm.format("    isOther         : %b%n", isOther());
    fm.format("    fileKey         : %s%n", fileKey());
    fm.format("    size            : %d%n", size());
    fm.format("    compressedSize  : %d%n", compressedSize());
    fm.format("    crc             : %x%n", crc());
    fm.format("    method          : %d%n", method());
    fm.close();
    return sb.toString();
}

4. CasEnvironmentContextListener#collectEnvironmentInfo()

Project: passport
File: CasEnvironmentContextListener.java
/**
     * Collect environment info with
     * details on the java and os deployment
     * versions.
     *
     * @return environment info
     */
private String collectEnvironmentInfo() {
    final Properties properties = System.getProperties();
    final Formatter formatter = new Formatter();
    formatter.format("\n******************** Welcome to CAS ********************\n");
    formatter.format("CAS Version: %s\n", CasVersion.getVersion());
    formatter.format("Java Home: %s\n", properties.get("java.home"));
    formatter.format("Java Vendor: %s\n", properties.get("java.vendor"));
    formatter.format("Java Version: %s\n", properties.get("java.version"));
    formatter.format("OS Architecture: %s\n", properties.get("os.arch"));
    formatter.format("OS Name: %s\n", properties.get("os.name"));
    formatter.format("OS Version: %s\n", properties.get("os.version"));
    formatter.format("*******************************************************\n");
    return formatter.toString();
}

5. StockName#main()

Project: openjdk
File: StockName.java
public static void main(String[] args) {
    StockName sn = new StockName("HUGE", "Huge Fruit, Inc.", "Fruit Titanesque, Inc.");
    CharBuffer cb = CharBuffer.allocate(128);
    Formatter fmt = new Formatter(cb);
    //   -> "Huge Fruit, Inc."
    fmt.format("%s", sn);
    test(cb, "Huge Fruit, Inc.");
    //   -> "HUGE - Huge Fruit, Inc."
    fmt.format("%s", sn.toString());
    test(cb, "HUGE - Huge Fruit, Inc.");
    //   -> "HUGE"
    fmt.format("%#s", sn);
    test(cb, "HUGE");
    //   -> "HUGE      "
    fmt.format("%-10.8s", sn);
    test(cb, "HUGE      ");
    //   -> "Huge Fruit,*"
    fmt.format("%.12s", sn);
    test(cb, "Huge Fruit,*");
    fmt.format(Locale.FRANCE, "%25s", sn);
    //   -> "   Fruit Titanesque, Inc."
    test(cb, "   Fruit Titanesque, Inc.");
}

6. StockName#main()

Project: jdk7u-jdk
File: StockName.java
public static void main(String[] args) {
    StockName sn = new StockName("HUGE", "Huge Fruit, Inc.", "Fruit Titanesque, Inc.");
    CharBuffer cb = CharBuffer.allocate(128);
    Formatter fmt = new Formatter(cb);
    //   -> "Huge Fruit, Inc."
    fmt.format("%s", sn);
    test(cb, "Huge Fruit, Inc.");
    //   -> "HUGE - Huge Fruit, Inc."
    fmt.format("%s", sn.toString());
    test(cb, "HUGE - Huge Fruit, Inc.");
    //   -> "HUGE"
    fmt.format("%#s", sn);
    test(cb, "HUGE");
    //   -> "HUGE      "
    fmt.format("%-10.8s", sn);
    test(cb, "HUGE      ");
    //   -> "Huge Fruit,*"
    fmt.format("%.12s", sn);
    test(cb, "Huge Fruit,*");
    fmt.format(Locale.FRANCE, "%25s", sn);
    //   -> "   Fruit Titanesque, Inc."
    test(cb, "   Fruit Titanesque, Inc.");
}

7. AppendableLoggerTest#testAppendableLogger()

Project: uPortal
File: AppendableLoggerTest.java
@Test
public void testAppendableLogger() {
    final Logger logger = Mockito.mock(Logger.class);
    final Formatter f = new Formatter(new AppendableLogger(logger, LogLevel.INFO));
    f.format("%9s | %16s | %16s%n", "Data Type", "Export Supported", "Import Supported");
    verify(logger).info("Data Type | Export Supported | Import Supported");
    f.format("%9s | %16s | %16s%n", "portlet-type", true, true);
    verify(logger).info("portlet-type |             true |             true");
    f.format("%9s | %16s | %16s%n", "portlet-definition", true, false);
    verify(logger).info("portlet-definition |             true |            false");
    f.format("%9s | %16s | %16s%n", "layout", true, false);
    verify(logger).info("   layout |             true |            false");
    verifyNoMoreInteractions(logger);
}

8. Varargs#main()

Project: checker-framework
File: Varargs.java
public static void main(String... p) {
    Formatter f = new Formatter();
    // vararg as parameter
    //:: warning: non-varargs call of varargs method with inexact argument type for last parameter; :: warning: (format.indirect.arguments)
    // equivalent to (Object[])null
    f.format("Nothing", null);
    //:: warning: (format.indirect.arguments)
    f.format("Nothing", (Object[]) null);
    //:: warning: (format.indirect.arguments)
    f.format("%s", (Object[]) null);
    //:: warning: (format.indirect.arguments)
    f.format("%s %d %x", (Object[]) null);
    //:: warning: non-varargs call of varargs method with inexact argument type for last parameter; :: warning: (format.indirect.arguments)
    // equivalent to (Object[])null
    f.format("%s %d %x", null);
    //:: warning: (format.indirect.arguments)
    f.format("%d", new Object[1]);
    //:: warning: (format.indirect.arguments)
    f.format("%s", new Object[2]);
    //:: warning: (format.indirect.arguments)
    f.format("%s %s", new Object[0]);
    //:: warning: (format.indirect.arguments)
    f.format("Empty", new Object[0]);
    //:: warning: (format.indirect.arguments)
    f.format("Empty", new Object[5]);
    f.format("%s", new ArrayList<Object>());
    f.format("%d %s", 132, new Object[2]);
    f.format("%s %d", new Object[2], 123);
    //:: error: (format.missing.arguments)
    f.format("%d %s %s", 132, new Object[2]);
    //:: error: (argument.type.incompatible)
    f.format("%d %d", new Object[2], 123);
    //:: error: (format.specifier.null) :: warning: (format.indirect.arguments)
    f.format("%d %<f", new Object[1]);
    // too many arguments
    //:: warning: (format.excess.arguments)
    f.format("", 213);
    //:: warning: (format.excess.arguments)
    f.format("%d", 232, 132);
    //:: warning: (format.excess.arguments)
    f.format("%s", "a", "b");
    //:: warning: (format.excess.arguments)
    f.format("%d %s", 123, "a", 123);
    // too few arguments
    //:: error: (format.missing.arguments)
    f.format("%s");
    //:: error: (format.missing.arguments)
    f.format("%d %s", 545);
    //:: error: (format.missing.arguments)
    f.format("%s %c %c", 'c', 'c');
    f.close();
}

9. GitPlugin#created()

Project: bnd
File: GitPlugin.java
@Override
public void created(Project p) throws Exception {
    Formatter f = new Formatter();
    f.format("/%s/\n", p.getProperty(Constants.DEFAULT_PROP_TARGET_DIR, "generated"));
    f.format("/%s/\n", p.getProperty(Constants.DEFAULT_PROP_BIN_DIR, "bin"));
    f.format("/%s/\n", p.getProperty(Constants.DEFAULT_PROP_TESTBIN_DIR, "bin_test"));
    IO.store(f.toString(), p.getFile(GITIGNORE));
    f.close();
    //
    for (File dir : p.getSourcePath()) {
        touch(dir);
    }
    touch(p.getTestSrc());
}

10. RemoteTest#testTransform()

Project: bnd
File: RemoteTest.java
public void testTransform() throws Exception {
    File file = new File(sourceDir, "list");
    Formatter f = new Formatter();
    f.format("%s\n", IO.getFile(sourceDir, "a.txt").getAbsolutePath());
    f.format("%s\n", IO.getFile(sourceDir, "b.txt").getAbsolutePath());
    f.format("%s\n", IO.getFile("bnd.bnd").getAbsolutePath());
    IO.store(f.toString(), file);
    f.close();
    source.update(file);
    source.sync();
    assertTrue(IO.getFile(sinkDir, "areas/test/cwd/a.txt").isFile());
    assertTrue(IO.getFile(sinkDir, "areas/test/cwd/b.txt").isFile());
    assertTrue(IO.getFile(sinkDir, "areas/test/cwd/list").isFile());
    assertTrue(IO.getFile(sinkDir, "shacache/9124D0084FC1DECD361E82332F535E6371496CEB").isFile());
    assertTrue(IO.getFile(sinkDir, "shacache/A6A4DB850D85C513F549A51A3315A67B50EA86F2").isFile());
    assertTrue(IO.getFile(sinkDir, "areas/test/cwd/_ABS").isDirectory());
}

11. DebugOneProviderOnlyAppStartupTest#testLogOneProvider()

Project: wink
File: DebugOneProviderOnlyAppStartupTest.java
/**
     * Tests that a Provider is logged at the debug level.
     */
public void testLogOneProvider() throws Exception {
    List<LogRecord> records = handler.getRecords();
    assertEquals(Level.INFO, records.get(11).getLevel());
    assertEquals("The class org.apache.wink.server.serviceability.DebugOneProviderOnlyAppStartupTest$Provider1 was registered as a JAX-RS MessageBodyWriter provider for all Java types and */* media types.", records.get(11).getMessage());
    assertEquals(Level.FINE, records.get(12).getLevel());
    StringBuffer sb = new StringBuffer();
    Formatter f = new Formatter(sb);
    f.format("The following JAX-RS MessageBodyWriter providers are registered:%n");
    f.format("Produces Media Type                 Generic Type              Custom?  Provider Class%n");
    f.format("*/*                                 Object                    true     org.apache.wink.server.serviceability.DebugOneProviderOnlyAppStartupTest$Provider1");
    assertEquals(sb.toString(), records.get(12).getMessage());
    assertEquals(13, records.size());
}

12. CountPerTypeListener#update()

Project: esper
File: CountPerTypeListener.java
public void update(EventBean[] newEvents, EventBean[] oldEvents) {
    Formatter outFormatter = new Formatter(new StringBuffer());
    outFormatter.format("%10s | %10s\n", "type", "count");
    outFormatter.format("---------- | ----------\n");
    int total = 0;
    for (int i = 0; i < newEvents.length; i++) {
        String type = (String) newEvents[i].get("type");
        long count = (Long) newEvents[i].get("countPerType");
        outFormatter.format("%10s | %10s\n", type, count);
        total += count;
    }
    outFormatter.format("%10s | %10s\n", "total =", total);
    complexEventListener.onComplexEvent("Current count per type:\n" + outFormatter.out().toString());
}

13. ReadEventCycleSummary#toString()

Project: databus
File: ReadEventCycleSummary.java
@Override
public String toString() {
    StringBuilder sb = new StringBuilder(256);
    Formatter fmt = new Formatter(sb);
    double prodRate = _elapsedTimeMillis == 0 ? 0 : (double) _sizeInBytes / _elapsedTimeMillis;
    double consRate = _readMillis == 0 ? 0 : (double) _sizeInBytes / _readMillis;
    fmt.format(EventReaderSummary.EVENT_LOG_FORMAT, _eventSourceName, 0, _sourceSummaries.size(), _totalEventNum, _endOfWindowScn, _readMillis, _sizeInBytes, _eventMillis, _elapsedTimeMillis, _queryTimeMillis, prodRate, consRate);
    fmt.flush();
    return fmt.toString();
}

14. EventReaderSummary#toString()

Project: databus
File: EventReaderSummary.java
@Override
public String toString() {
    StringBuilder sb = new StringBuilder(256);
    Formatter fmt = new Formatter(sb);
    long timeElapsed = getTimeElapsed();
    double prodRate = timeElapsed == 0 ? 0 : (double) _sizeOfSerializedEvents / timeElapsed;
    double consRate = _readMillis == 0 ? 0 : (double) _sizeOfSerializedEvents / _readMillis;
    fmt.format(EVENT_LOG_FORMAT, _sourceName, _sourceId, 1, _numberOfEvents, _endOfPeriodSCN, _readMillis, _sizeOfSerializedEvents, _msEvent, timeElapsed, _queryExecTime, prodRate, consRate);
    fmt.flush();
    return fmt.toString();
}

15. DtailPrinter#printStats()

Project: databus
File: DtailPrinter.java
public void printStats() {
    if (0 == _winNum)
        _winNum = 1;
    long elapsedMs = _endTs - _startTs;
    Formatter fmt = new Formatter();
    fmt.format(GLOBAL_STATS_FORMAT, elapsedMs, _eventsNum, (1000.0 * _eventsNum / elapsedMs), _winNum, (1000.0 * _winNum / elapsedMs), _payloadBytes, (1000.0 * _payloadBytes / elapsedMs), _payloadBytes / _eventsNum, _eventBytes, (1000.0 * _eventBytes / elapsedMs), 1.0 * _eventLagNs / (1000000L * _eventsNum));
    fmt.flush();
    fmt.close();
    String statsStr = fmt.toString();
    try {
        _out.write(statsStr.getBytes(Charset.defaultCharset()));
        _out.flush();
    } catch (IOException e) {
        LOG.error("unable to write stats", e);
    }
}

16. AliasContribution#toString()

Project: tapestry5
File: AliasContribution.java
@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    Formatter formatter = new Formatter(builder);
    formatter.format("<AliasContribution: %s", contributionType.getName());
    if (InternalUtils.isNonBlank(mode))
        formatter.format(" mode:%s", mode);
    formatter.format(" %s>", object);
    return builder.toString();
}

17. EhCacheStatistics#toString()

Project: passport
File: EhCacheStatistics.java
@Override
public void toString(final StringBuilder builder) {
    final String name = this.getName();
    if (StringUtils.isNotBlank(name)) {
        builder.append(name).append(':');
    }
    final int free = getPercentFree();
    final Formatter formatter = new Formatter(builder);
    if (useBytes) {
        formatter.format("%.2f", heapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
        builder.append("MB heap, ");
        formatter.format("%.2f", diskSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
        builder.append("MB disk, ");
    } else {
        builder.append(heapSize).append(" items in heap, ");
        builder.append(diskSize).append(" items on disk, ");
    }
    formatter.format("%.2f", offHeapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
    builder.append("MB off-heap, ");
    builder.append(free).append("% free, ");
    builder.append(getEvictions()).append(" evictions");
    formatter.close();
}

18. AbstractTCKTest#dumpSerialStream()

Project: openjdk
File: AbstractTCKTest.java
/**
     * Utility method to dump a byte array in a java syntax.
     * @param bytes and array of bytes
     * @return a string containing the bytes formatted in java syntax
     */
protected static String dumpSerialStream(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 5);
    Formatter fmt = new Formatter(sb);
    fmt.format("    byte[] bytes = {");
    final int linelen = 10;
    for (int i = 0; i < bytes.length; i++) {
        if (i % linelen == 0) {
            fmt.format("%n        ");
        }
        fmt.format(" %3d,", bytes[i] & 0xff);
        if ((i % linelen) == (linelen - 1) || i == bytes.length - 1) {
            fmt.format("  /*");
            int s = i / linelen * linelen;
            int k = i % linelen;
            for (int j = 0; j <= k && s + j < bytes.length; j++) {
                fmt.format(" %c", bytes[s + j] & 0xff);
            }
            fmt.format(" */");
        }
    }
    fmt.format("%n    };%n");
    return sb.toString();
}

19. AbstractVector#toString()

Project: matrix-toolkits-java
File: AbstractVector.java
@Override
public String toString() {
    // Output into coordinate format. Indices start from 1 instead of 0
    Formatter out = new Formatter();
    out.format("%10d %19d\n", size, Matrices.cardinality(this));
    int i = 0;
    for (VectorEntry e : this) {
        if (e.get() != 0)
            out.format("%10d % .12e\n", e.index() + 1, e.get());
        if (++i == 100) {
            out.format("...\n");
            break;
        }
    }
    return out.toString();
}

20. AbstractMatrix#toString()

Project: matrix-toolkits-java
File: AbstractMatrix.java
@Override
public String toString() {
    // Output into coordinate format. Indices start from 1 instead of 0
    Formatter out = new Formatter();
    out.format("%10d %10d %19d%n", numRows, numColumns, Matrices.cardinality(this));
    int i = 0;
    for (MatrixEntry e : this) {
        if (e.get() != 0)
            out.format("%10d %10d % .12e\n", e.row() + 1, e.column() + 1, e.get());
        if (++i == 100) {
            out.format("...\n");
            break;
        }
    }
    return out.toString();
}

21. SortsTiming#showComparison()

Project: java-algorithms-implementation
File: SortsTiming.java
private static final void showComparison() {
    StringBuilder resultsBuilder = new StringBuilder();
    resultsBuilder.append("Number of integers = ").append(SIZE).append("\n");
    String format = "%-32s%-15s%-15s%-15s\n";
    Formatter formatter = new Formatter(resultsBuilder, Locale.US);
    formatter.format(format, "Algorithm", "Random", "Sorted", "Reverse Sorted");
    for (int i = 0; i < names.length; i++) {
        if (names[i] == null)
            break;
        formatter.format(format, names[i], FORMAT.format(results[i][0]), FORMAT.format(results[i][1]), FORMAT.format(results[i][2]));
    }
    formatter.close();
    System.out.println(resultsBuilder.toString());
}

22. DBRef#toPDB()

Project: biojava
File: DBRef.java
/** Append the PDB representation of this DBRef to the provided StringBuffer
	 *
	 * @param buf the StringBuffer to write to.
	 */
@Override
public void toPDB(StringBuffer buf) {
    Formatter formatter = new Formatter(new StringBuilder(), Locale.UK);
    //        DBREF  3ETA A  990  1295  UNP    P06213   INSR_HUMAN    1017   1322
    //        DBREF  3EH2 A    2   767  UNP    P53992   SC24C_HUMAN    329   1094
    //        DBREF 3EH2 A    2   767     UNP   P53992  SC24C_HUMAN   329   1094
    //        DBREF  3ETA A  990  1295  UNP    P06213   INSR_HUMAN    1017   1322
    formatter.format("DBREF  %4s %1s %4d%1s %4d%1s %-6s %-8s %-12s%6d%1c%6d%1c            ", idCode, chainId, seqbegin, insertBegin, seqEnd, insertEnd, database, dbAccession, dbIdCode, dbSeqBegin, idbnsBegin, dbSeqEnd, idbnsEnd);
    buf.append(formatter.toString());
    formatter.close();
}

23. AlbianLoggerService#getMessage()

Project: Albianj2
File: AlbianLoggerService.java
protected String getMessage(String level, String format, Object... values) {
    IStackTrace trace = RuningTrace.getTraceInfo();
    StringBuilder sb = new StringBuilder();
    @SuppressWarnings("resource") Formatter f = new Formatter(sb);
    f.format("%s.Trace:%s.", level, trace.toString());
    if (null != values)
        f.format(format, values);
    if (!Validate.isNullOrEmptyOrAllSpace(KernelSetting.getAppName())) {
        return KernelSetting.getAppName() + " " + f.toString();
    }
    return f.toString();
}

24. AlbianLoggerService#getMessage()

Project: Albianj2
File: AlbianLoggerService.java
protected String getMessage(String level, Exception e, String format, Object... values) {
    IStackTrace trace = RuningTrace.getTraceInfo(e);
    StringBuilder sb = new StringBuilder();
    @SuppressWarnings("resource") Formatter f = new Formatter(sb);
    f.format("%s.Trace:%s,Exception:%s.", level, trace.toString(), e.getMessage());
    if (null != values)
        f.format(format, values);
    if (!Validate.isNullOrEmptyOrAllSpace(KernelSetting.getAppName())) {
        return KernelSetting.getAppName() + " " + f.toString();
    }
    return f.toString();
}

25. PDF417ScanningDecoder#toString()

Project: weex
File: PDF417ScanningDecoder.java
public static String toString(BarcodeValue[][] barcodeMatrix) {
    Formatter formatter = new Formatter();
    for (int row = 0; row < barcodeMatrix.length; row++) {
        formatter.format("Row %2d: ", row);
        for (int column = 0; column < barcodeMatrix[row].length; column++) {
            BarcodeValue barcodeValue = barcodeMatrix[row][column];
            if (barcodeValue.getValue().length == 0) {
                formatter.format("        ", (Object[]) null);
            } else {
                formatter.format("%4d(%2d)", barcodeValue.getValue()[0], barcodeValue.getConfidence(barcodeValue.getValue()[0]));
            }
        }
        formatter.format("%n");
    }
    String result = formatter.toString();
    formatter.close();
    return result;
}

26. DetectionResultColumn#toString()

Project: weex
File: DetectionResultColumn.java
@Override
public String toString() {
    Formatter formatter = new Formatter();
    int row = 0;
    for (Codeword codeword : codewords) {
        if (codeword == null) {
            formatter.format("%3d:    |   %n", row++);
            continue;
        }
        formatter.format("%3d: %3d|%3d%n", row++, codeword.getRowNumber(), codeword.getValue());
    }
    String result = formatter.toString();
    formatter.close();
    return result;
}

27. Option#toString()

Project: processors
File: Option.java
/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
public String toString() {
    int splitsize = 45;
    final StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb);
    formatter.format("%-20s ", getName());
    if (isAmbiguous()) {
        formatter.format("*");
    } else {
        sb.append(" ");
    }
    if (getFlag() != null) {
        formatter.format("(%4s) : ", "-" + getFlag());
    } else {
        sb.append("       : ");
    }
    int r = shortDescription.length() / splitsize;
    for (int i = 0; i <= r; i++) {
        if (shortDescription.substring(splitsize * i).length() <= splitsize) {
            formatter.format(((i == 0) ? "%s" : "%28s") + "%-45s\n", "", shortDescription.substring(splitsize * i));
        } else {
            formatter.format(((i == 0) ? "%s" : "%28s") + "%-45s\n", "", shortDescription.substring(splitsize * i, splitsize * i + splitsize));
        }
    }
    return sb.toString();
}

28. Detector#wordProbToString()

Project: lumify
File: Detector.java
private String wordProbToString(double[] prob) {
    Formatter formatter = new Formatter();
    for (int j = 0; j < prob.length; ++j) {
        double p = prob[j];
        if (p >= 0.00001) {
            formatter.format(" %s:%.5f", langlist.get(j), p);
        }
    }
    String string = formatter.toString();
    formatter.close();
    return string;
}

29. UDP#dumpSocketInfo()

Project: JGroups
File: UDP.java
protected String dumpSocketInfo() throws Exception {
    StringBuilder sb = new StringBuilder(128);
    Formatter formatter = new Formatter(sb);
    formatter.format("mcast_addr=%s, bind_addr=%s, ttl=%d", mcast_addr, bind_addr, ip_ttl);
    if (sock != null)
        formatter.format("\nsock: bound to %s:%d, receive buffer size=%d, send buffer size=%d", sock.getLocalAddress().getHostAddress(), sock.getLocalPort(), sock.getReceiveBufferSize(), sock.getSendBufferSize());
    if (mcast_sock != null)
        formatter.format("\nmcast_sock: bound to %s:%d, send buffer size=%d, receive buffer size=%d", mcast_sock.getInterface().getHostAddress(), mcast_sock.getLocalPort(), mcast_sock.getSendBufferSize(), mcast_sock.getReceiveBufferSize());
    return sb.toString();
}

30. SliderCrankTest#step()

Project: jbox2d
File: SliderCrankTest.java
@Override
public void step(TestbedSettings settings) {
    super.step(settings);
    addTextLine("Keys: (f) toggle friction, (m) toggle motor");
    float torque = m_joint1.getMotorTorque(1);
    Formatter f = new Formatter();
    addTextLine(f.format("Friction: %b, Motor Force = %5.0f, ", m_joint2.isMotorEnabled(), torque).toString());
    f.close();
}

31. WebServer#baseFor()

Project: isis
File: WebServer.java
private String baseFor(final Server jettyServer) {
    final ServerConnector connector = (ServerConnector) jettyServer.getConnectors()[0];
    final String scheme = "http";
    final String host = ArrayExtensions.coalesce(connector.getHost(), "localhost");
    final int port = connector.getPort();
    final WebAppContext handler = (WebAppContext) jettyServer.getHandler();
    final String contextPath = handler.getContextPath();
    final StringBuilder buf = new StringBuilder();
    final Formatter formatter = new Formatter(buf);
    formatter.format("%s://%s:%d/%s", scheme, host, port, contextPath);
    return appendSlashIfRequired(buf).toString();
}

32. SizeAdapter#getView()

Project: digitalocean-swimmer
File: SizeAdapter.java
public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if (convertView == null)
        vi = inflater.inflate(R.layout.size_list_row, parent, false);
    final Size size = data.get(position);
    TextView ramcpuTextView = (TextView) vi.findViewById(R.id.ramcpuTextView);
    TextView diskTextView = (TextView) vi.findViewById(R.id.diskTextView);
    TextView transferTextView = (TextView) vi.findViewById(R.id.transferTextView);
    TextView monthlyPriceTextView = (TextView) vi.findViewById(R.id.monthlyPriceTextView);
    TextView hourlyPriceTextView = (TextView) vi.findViewById(R.id.hourlyPriceTextView);
    ramcpuTextView.setText(size.getSlug().toUpperCase(Locale.US) + "/" + size.getCpu() + "CPU");
    diskTextView.setText(size.getDisk() + "GB SSD DISK");
    transferTextView.setText(size.getTransfer() + "TB TRANSFER");
    Formatter formatter = new Formatter();
    monthlyPriceTextView.setText("$" + size.getCostPerMonth() + "/mo");
    hourlyPriceTextView.setText("$" + formatter.format("%1.5f", size.getCostPerHour()) + "/hour");
    formatter.close();
    return vi;
}

33. HttpRequestLoggingHandler#logConnectionEnd()

Project: databus
File: HttpRequestLoggingHandler.java
private void logConnectionEnd() {
    StringBuilder logLineBuilder = new StringBuilder(10000);
    boolean outbound = _connRequestNano > -1;
    Formatter logFormatter = new Formatter(logLineBuilder);
    logFormatter.format(CONNECT_LINE_FORMAT, outbound ? OUTBOUND_DIR : INBOUND_DIR, _peerId, "CONNECT", "/END", 0, 200, 0.0, outbound ? (System.nanoTime() - _connStartNano) * 1.0 / 1000000.0 : 0.0, _connBytes);
    log(outbound, logFormatter);
}

34. HttpRequestLoggingHandler#logConnectionStart()

Project: databus
File: HttpRequestLoggingHandler.java
private void logConnectionStart() {
    StringBuilder logLineBuilder = new StringBuilder(10000);
    boolean outbound = _connRequestNano > -1;
    java.util.Formatter logFormatter = new Formatter(logLineBuilder);
    logFormatter.format(CONNECT_LINE_FORMAT, outbound ? OUTBOUND_DIR : INBOUND_DIR, _peerId, "CONNECT", "/START", 0, 200, 0.0, outbound ? (System.nanoTime() - _connRequestNano) * 1.0 / 1000000.0 : 0.0, 0);
    log(outbound, logFormatter);
}

35. BootstrapApplierThread#setTabPosition()

Project: databus
File: BootstrapApplierThread.java
private void setTabPosition(int srcid, int logid, int tabRid, long windowScn) throws SQLException {
    PreparedStatement stmt = getTabPositionUpdateStmt();
    stmt.setInt(1, logid);
    stmt.setInt(2, tabRid);
    stmt.setLong(3, windowScn);
    stmt.setInt(4, srcid);
    stmt.executeUpdate();
    StringBuilder logLineBuilder = new StringBuilder(1024);
    Formatter logFormatter = new Formatter(logLineBuilder);
    logFormatter.format(APPLIER_STATE_LINE_FORMAT, srcid, logid, tabRid, windowScn);
    log(srcid, logFormatter);
}

36. FactoryCreateRule#toString()

Project: commons-digester
File: FactoryCreateRule.java
/**
     * {@inheritDoc}
     */
@Override
public String toString() {
    Formatter formatter = new Formatter().format("FactoryCreateRule[className=%s, attributeName=%s", className, attributeName);
    if (creationFactory != null) {
        formatter.format(", creationFactory=%s", creationFactory);
    }
    formatter.format("]");
    return (formatter.toString());
}

37. CallMethodRule#toString()

Project: commons-digester
File: CallMethodRule.java
/**
     * {@inheritDoc}
     */
@Override
public String toString() {
    Formatter formatter = new Formatter().format("CallMethodRule[methodName=%s, paramCount=%s, paramTypes={", methodName, paramCount);
    if (paramTypes != null) {
        for (int i = 0; i < paramTypes.length; i++) {
            formatter.format("%s%s", (i > 0 ? ", " : ""), (paramTypes[i] != null ? paramTypes[i].getName() : "null"));
        }
    }
    formatter.format("}]");
    return (formatter.toString());
}

38. BuildLogger#toString()

Project: bndtools
File: BuildLogger.java
public String toString(String name) {
    long end = System.currentTimeMillis();
    full("Duration %.2f sec", (end - start) / 1000f);
    StringBuilder top = new StringBuilder();
    Formatter topper = new Formatter(top);
    if (files > 0)
        topper.format("BUILD %s %d file%s built", name, files, files > 1 ? "s were" : " was");
    else
        topper.format("BUILD %s no build", name);
    topper.close();
    return top.append('\n').append(sb).toString();
}

39. MavenPlugin#augmentSetup()

Project: bnd
File: MavenPlugin.java
@Override
public String augmentSetup(String setup, String alias, Map<String, String> parameters) throws Exception {
    Formatter f = new Formatter();
    f.format("%s", setup);
    try {
        f.format("\n#\n# Change disk layout to fit maven\n#\n\n");
        f.format("-outputmask = ${@bsn}-${version;===S;${@version}}.jar\n");
        f.format("src=src/main/java\n");
        f.format("bin=target/classes\n");
        f.format("testsrc=src/test/java\n");
        f.format("testbin=target/test-classes\n");
        f.format("target-dir=target\n");
        return f.toString();
    } finally {
        f.close();
    }
}

40. bnd#_syntax()

Project: bnd
File: bnd.java
@Description("Access the internal bnd database of keywords and options")
public void _syntax(syntaxOptions opts) throws Exception {
    int w = opts.width() < 80 ? 120 : opts.width();
    Justif justif = new Justif(w, opts.width(), 40, 42, w - 10);
    List<String> args = opts._arguments();
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    for (String s : args) {
        f.format(" \n[%s]\n", s);
        Syntax sx = Syntax.HELP.get(s);
        if (s == null)
            f.format("Unknown");
        else {
            print(f, sx, "  ");
        }
    }
    f.flush();
    justif.wrap(sb);
    err.println(sb);
}

41. CommandLine#help()

Project: bnd
File: CommandLine.java
private String help(Object target, String cmd, Class<? extends Options> type) throws Exception {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    if (cmd == null)
        help(f, target);
    else if (type == null)
        help(f, target, cmd);
    else
        help(f, target, cmd, type);
    f.flush();
    justif.wrap(sb);
    return sb.toString();
}

42. UnicodeRepresentation#escapeUnicode()

Project: assertj-core
File: UnicodeRepresentation.java
private static String escapeUnicode(String input) {
    StringBuilder b = new StringBuilder(input.length());
    Formatter formatter = new Formatter(b);
    for (char c : input.toCharArray()) {
        if (c < 128) {
            b.append(c);
        } else {
            formatter.format("\\u%04x", (int) c);
        }
    }
    formatter.close();
    return b.toString();
}

43. PDF417ScanningDecoder#toString()

Project: zxing
File: PDF417ScanningDecoder.java
public static String toString(BarcodeValue[][] barcodeMatrix) {
    Formatter formatter = new Formatter();
    for (int row = 0; row < barcodeMatrix.length; row++) {
        formatter.format("Row %2d: ", row);
        for (int column = 0; column < barcodeMatrix[row].length; column++) {
            BarcodeValue barcodeValue = barcodeMatrix[row][column];
            if (barcodeValue.getValue().length == 0) {
                formatter.format("        ", (Object[]) null);
            } else {
                formatter.format("%4d(%2d)", barcodeValue.getValue()[0], barcodeValue.getConfidence(barcodeValue.getValue()[0]));
            }
        }
        formatter.format("%n");
    }
    String result = formatter.toString();
    formatter.close();
    return result;
}

44. DetectionResultColumn#toString()

Project: zxing
File: DetectionResultColumn.java
@Override
public String toString() {
    Formatter formatter = new Formatter();
    int row = 0;
    for (Codeword codeword : codewords) {
        if (codeword == null) {
            formatter.format("%3d:    |   %n", row++);
            continue;
        }
        formatter.format("%3d: %3d|%3d%n", row++, codeword.getRowNumber(), codeword.getValue());
    }
    String result = formatter.toString();
    formatter.close();
    return result;
}

45. MavenILogger#info()

Project: android-maven-plugin
File: MavenILogger.java
@Override
public void info(@NonNull String s, Object... objects) {
    final Formatter formatter = new Formatter();
    if (verboseInfo) {
        log.debug(formatter.format(s, objects).out().toString());
    } else {
        log.info(formatter.format(s, objects).out().toString());
    }
}

46. Log#formatMsg()

Project: wwmmo
File: Log.java
/**
   * Formats the given message. If the last argument is an exception, we'll append the exception to
   * the end of the message.
   */
private static String formatMsg(String fmt, Object[] args) {
    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb, Locale.ENGLISH);
    try {
        formatter.format(fmt, args);
    } catch (Exception e) {
        return fmt;
    } finally {
        formatter.close();
    }
    if (args != null && args.length >= 1 && args[args.length - 1] instanceof Throwable) {
        Throwable throwable = (Throwable) args[args.length - 1];
        StringWriter writer = new StringWriter();
        throwable.printStackTrace(new PrintWriter(writer));
        sb.append("\n");
        sb.append(writer.toString());
    }
    return sb.toString();
}

47. PortalDataHandlerServiceUtils#format()

Project: uPortal
File: PortalDataHandlerServiceUtils.java
public static void format(Iterable<? extends IPortalData> data, Logger l) {
    final Formatter f = new Formatter(new AppendableLogger(l, LogLevel.INFO));
    final TableFormatter tableFormatter = new TableFormatter(new TableEntry<String>("sysid", "-", "s"), new TableEntry<String>("Description", "-", "s"));
    for (final IPortalData it : data) {
        final String dataId = it.getDataId();
        String dataTitle = it.getDataTitle();
        if (dataTitle == null || dataTitle.equals(dataId)) {
            dataTitle = "";
        }
        tableFormatter.addRow(new TableEntry<String>(dataId, "-", "s"), new TableEntry<String>(dataTitle, "-", "s"));
    }
    tableFormatter.format(f);
}

48. LocationImpl#toString()

Project: tapestry5
File: LocationImpl.java
@Override
public String toString() {
    StringBuilder buffer = new StringBuilder(resource.toString());
    Formatter formatter = new Formatter(buffer);
    if (line != UNKNOWN)
        formatter.format(", line %d", line);
    if (column != UNKNOWN)
        formatter.format(", column %d", column);
    return buffer.toString();
}

49. LocationImpl#toString()

Project: tapestry-5
File: LocationImpl.java
@Override
public String toString() {
    StringBuilder buffer = new StringBuilder(resource.toString());
    Formatter formatter = new Formatter(buffer);
    if (line != UNKNOWN)
        formatter.format(", line %d", line);
    if (column != UNKNOWN)
        formatter.format(", column %d", column);
    return buffer.toString();
}

50. OracleLobAvroImportTest#getBlobInsertStr()

Project: sqoop
File: OracleLobAvroImportTest.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 {
        for (byte b : blobData.getBytes("UTF-8")) {
            fmt.format("%02X", b);
        }
    } catch (UnsupportedEncodingException uee) {
        fail("Could not get utf-8 bytes for blob string");
        return null;
    }
    sb.append("'");
    return sb.toString();
}

51. OracleCompatTest#getBlobInsertStr()

Project: sqoop
File: 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 {
        for (byte b : blobData.getBytes("UTF-8")) {
            fmt.format("%02X", b);
        }
    } catch (UnsupportedEncodingException uee) {
        fail("Could not get utf-8 bytes for blob string");
        return null;
    }
    sb.append("'");
    return sb.toString();
}

52. StringFormat#get()

Project: SchemaCrawler
File: StringFormat.java
@Override
public String get() {
    if (isBlank(format) || args == null || args.length == 0) {
        return format;
    }
    try (final Formatter formatter = new Formatter()) {
        return formatter.format(format, args).toString();
    }
}

53. AbstractImmutableVector#toString()

Project: reef
File: AbstractImmutableVector.java
@SuppressWarnings("boxing")
@Override
public String toString() {
    final StringBuilder b = new StringBuilder("DenseVector(");
    try (final Formatter formatter = new Formatter(b, Locale.US)) {
        final int size = Math.min(25, this.size());
        for (int i = 0; i < size; ++i) {
            if (i < size - 1) {
                formatter.format("%1.3f, ", this.get(i));
            } else {
                formatter.format("%1.3f ", this.get(i));
            }
        }
        if (this.size() > 25) {
            formatter.format("...");
        }
    }
    b.append(')');
    return b.toString();
}

54. EhCacheStatistics#toString()

Project: passport
File: EhCacheStatistics.java
@Override
public void toString(final StringBuilder builder) {
    final String name = this.getName();
    if (StringUtils.isNotBlank(name)) {
        builder.append(name).append(':');
    }
    final int free = getPercentFree();
    try (final Formatter formatter = new Formatter(builder)) {
        if (this.useBytes) {
            formatter.format("%.2f", this.heapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
            builder.append("MB heap, ");
            formatter.format("%.2f", this.diskSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
            builder.append("MB disk, ");
        } else {
            builder.append(this.heapSize).append(" items in heap, ");
            builder.append(this.diskSize).append(" items on disk, ");
        }
        formatter.format("%.2f", this.offHeapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
        builder.append("MB off-heap, ");
        builder.append(free).append("% free, ");
        builder.append(getEvictions()).append(" evictions");
    }
}

55. CasBanner#collectEnvironmentInfo()

Project: passport
File: CasBanner.java
/**
     * Collect environment info with
     * details on the java and os deployment
     * versions.
     *
     * @return environment info
     */
private static String collectEnvironmentInfo() {
    final Properties properties = System.getProperties();
    try (final Formatter formatter = new Formatter()) {
        formatter.format("\n******************** Welcome to CAS *******************\n");
        formatter.format("CAS Version: %s\n", CasVersion.getVersion());
        formatter.format("Build Date/Time: %s\n", CasVersion.getDateTime());
        formatter.format("Java Home: %s\n", properties.get("java.home"));
        formatter.format("Java Vendor: %s\n", properties.get("java.vendor"));
        formatter.format("Java Version: %s\n", properties.get("java.version"));
        formatter.format("OS Architecture: %s\n", properties.get("os.arch"));
        formatter.format("OS Name: %s\n", properties.get("os.name"));
        formatter.format("OS Version: %s\n", properties.get("os.version"));
        formatter.format("*******************************************************\n");
        return formatter.toString();
    }
}

56. SimpleCacheStatistics#toString()

Project: passport
File: SimpleCacheStatistics.java
@Override
public void toString(final StringBuilder builder) {
    if (this.name != null) {
        builder.append(this.name).append(':');
    }
    try (final Formatter formatter = new Formatter(builder)) {
        formatter.format("%.2f", this.size / BYTES_PER_MB);
        builder.append("MB used, ");
        builder.append(getPercentFree()).append("% free, ");
        builder.append(this.evictions).append(" evictions");
    }
}

57. TicketsResource#createTicketGrantingTicket()

Project: passport
File: TicketsResource.java
/**
     * Create new ticket granting ticket.
     *
     * @param requestBody username and password application/x-www-form-urlencoded values
     * @param request raw HttpServletRequest used to call this method
     * @return ResponseEntity representing RESTful response
     */
@RequestMapping(value = "/tickets", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public final ResponseEntity<String> createTicketGrantingTicket(@RequestBody final MultiValueMap<String, String> requestBody, final HttpServletRequest request) {
    try (Formatter fmt = new Formatter()) {
        final TicketGrantingTicket tgtId = this.cas.createTicketGrantingTicket(obtainCredential(requestBody));
        final URI ticketReference = new URI(request.getRequestURL().toString() + '/' + tgtId.getId());
        final HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ticketReference);
        headers.setContentType(MediaType.TEXT_HTML);
        fmt.format("<!DOCTYPE HTML PUBLIC \\\"-//IETF//DTD HTML 2.0//EN\\\"><html><head><title>");
        //IETF//DTD HTML 2.0//EN\\\"><html><head><title>");
        fmt.format("%s %s", HttpStatus.CREATED, HttpStatus.CREATED.getReasonPhrase()).format("</title></head><body><h1>TGT Created</h1><form action=\"%s", ticketReference.toString()).format("\" method=\"POST\">Service:<input type=\"text\" name=\"service\" value=\"\">").format("<br><input type=\"submit\" value=\"Submit\"></form></body></html>");
        return new ResponseEntity<String>(fmt.toString(), headers, HttpStatus.CREATED);
    } catch (final Throwable e) {
        LOGGER.error(e.getMessage(), e);
        return new ResponseEntity<String>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}

58. SimpleCacheStatistics#toString()

Project: passport
File: SimpleCacheStatistics.java
@Override
public void toString(final StringBuilder builder) {
    if (this.name != null) {
        builder.append(this.name).append(':');
    }
    try (final Formatter formatter = new Formatter(builder)) {
        formatter.format("%.2f", this.size / BYTES_PER_MB);
        builder.append("MB used, ");
        builder.append(getPercentFree()).append("% free, ");
        builder.append(this.evictions).append(" evictions");
    }
}

59. Http2Connection#toHexdump1()

Project: openjdk
File: Http2Connection.java
private static String toHexdump1(ByteBuffer bb) {
    bb.mark();
    StringBuilder sb = new StringBuilder(512);
    Formatter f = new Formatter(sb);
    while (bb.hasRemaining()) {
        int i = Byte.toUnsignedInt(bb.get());
        f.format("%02x:", i);
    }
    sb.deleteCharAt(sb.length() - 1);
    bb.reset();
    return sb.toString();
}

60. XMLLimitAnalyzer#debugPrint()

Project: openjdk
File: XMLLimitAnalyzer.java
public void debugPrint(XMLSecurityManager securityManager) {
    Formatter formatter = new Formatter();
    System.out.println(formatter.format("%30s %15s %15s %15s %30s", "Property", "Limit", "Total size", "Size", "Entity Name"));
    for (Limit limit : Limit.values()) {
        formatter = new Formatter();
        System.out.println(formatter.format("%30s %15d %15d %15d %30s", limit.name(), securityManager.getLimit(limit), totalValue[limit.ordinal()], values[limit.ordinal()], names[limit.ordinal()]));
    }
}

61. UserServiceBean#changePasswd()

Project: myWMS
File: UserServiceBean.java
public User changePasswd(User user, String passw, boolean checkWeakPassword) throws UserServiceException {
    MessageDigest md5;
    if (checkWeakPassword) {
        checkPassword(passw);
    }
    try {
        md5 = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException ex) {
        throw new IllegalArgumentException("cannot encrypt password");
    }
    md5.reset();
    md5.update(passw.getBytes());
    StringBuffer hexString = new StringBuffer(32);
    Formatter f = new Formatter(hexString);
    for (byte b : md5.digest()) {
        f.format("%02x", b);
    }
    String password = hexString.toString();
    user.setPassword(password);
    return user;
}

62. TrimVideoUtils#stringForTime()

Project: k4l-video-trimmer
File: TrimVideoUtils.java
public static String stringForTime(int timeMs) {
    int totalSeconds = timeMs / 1000;
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    Formatter mFormatter = new Formatter();
    if (hours > 0) {
        return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
    } else {
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
}

63. JCUtils#stringForTime()

Project: JieCaoVideoPlayer-develop
File: JCUtils.java
public static String stringForTime(int timeMs) {
    if (timeMs <= 0 || timeMs >= 24 * 60 * 60 * 1000) {
        return "00:00";
    }
    int totalSeconds = timeMs / 1000;
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    StringBuilder stringBuilder = new StringBuilder();
    Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
    if (hours > 0) {
        return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
    } else {
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
}

64. JCUtils#stringForTime()

Project: JieCaoVideoPlayer
File: JCUtils.java
public static String stringForTime(int timeMs) {
    if (timeMs <= 0 || timeMs >= 24 * 60 * 60 * 1000) {
        return "00:00";
    }
    int totalSeconds = timeMs / 1000;
    int seconds = totalSeconds % 60;
    int minutes = (totalSeconds / 60) % 60;
    int hours = totalSeconds / 3600;
    StringBuilder stringBuilder = new StringBuilder();
    Formatter mFormatter = new Formatter(stringBuilder, Locale.getDefault());
    if (hours > 0) {
        return mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
    } else {
        return mFormatter.format("%02d:%02d", minutes, seconds).toString();
    }
}

65. PCMAnalyser#toString()

Project: jackrabbit-oak
File: PCMAnalyser.java
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    @SuppressWarnings("resource") Formatter formatter = new Formatter(sb);
    if (pcms.isEmpty()) {
        formatter.format("No persisted compaction map found.%n");
    } else {
        formatter.format("Persisted compaction map info:%n");
        for (Deque<PCMInfo> pcm : pcms) {
            formatter.format("%s%n", pcm);
        }
        formatter.format("Persisted compaction map size:%n");
        sb.append(super.toString());
        formatter.format("%n");
        for (String e : errors) {
            formatter.format("%s%n", e);
        }
    }
    return sb.toString();
}

66. BufferedString#bytesToString()

Project: h2o-3
File: BufferedString.java
public String bytesToString() {
    StringBuilder sb = new StringBuilder(_len * 2);
    Formatter formatter = new Formatter(sb);
    boolean inHex = false;
    for (int i = 0; i < _len; i++) {
        if ((_buf[_off + i] & 0x80) == 128) {
            if (!inHex)
                sb.append("<0x");
            formatter.format("%02X", _buf[_off + i]);
            inHex = true;
        } else {
            // ASCII
            if (inHex) {
                sb.append(">");
                inHex = false;
            }
            formatter.format("%c", _buf[_off + i]);
        }
    }
    // close hex values as trailing char
    if (inHex)
        sb.append(">");
    return sb.toString();
}

67. Errors#childBindingAlreadySet()

Project: guice
File: Errors.java
public Errors childBindingAlreadySet(Key<?> key, Set<Object> sources) {
    Formatter allSources = new Formatter();
    for (Object source : sources) {
        if (source == null) {
            allSources.format("%n    (bound by a just-in-time binding)");
        } else {
            allSources.format("%n    bound at %s", source);
        }
    }
    Errors errors = addMessage("Unable to create binding for %s." + " It was already configured on one or more child injectors or private modules" + "%s%n" + "  If it was in a PrivateModule, did you forget to expose the binding?", key, allSources.out());
    return errors;
}

68. EhCacheStatistics#toString()

Project: cas
File: EhCacheStatistics.java
@Override
public void toString(final StringBuilder builder) {
    final String name = this.getName();
    if (StringUtils.isNotBlank(name)) {
        builder.append(name).append(':');
    }
    final int free = getPercentFree();
    try (final Formatter formatter = new Formatter(builder)) {
        if (this.useBytes) {
            formatter.format("%.2f", this.heapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
            builder.append("MB heap, ");
            formatter.format("%.2f", this.diskSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
            builder.append("MB disk, ");
        } else {
            builder.append(this.heapSize).append(" items in heap, ");
            builder.append(this.diskSize).append(" items on disk, ");
        }
        formatter.format("%.2f", this.offHeapSize / TOTAL_NUMBER_BYTES_IN_ONE_MEGABYTE);
        builder.append("MB off-heap, ");
        builder.append(free).append("% free, ");
        builder.append(getEvictions()).append(" evictions");
    }
}

69. CasBanner#collectEnvironmentInfo()

Project: cas
File: CasBanner.java
/**
     * Collect environment info with
     * details on the java and os deployment
     * versions.
     *
     * @return environment info
     */
private static String collectEnvironmentInfo() {
    final Properties properties = System.getProperties();
    try (final Formatter formatter = new Formatter()) {
        formatter.format("\n******************** Welcome to CAS *******************\n");
        formatter.format("CAS Version: %s\n", CasVersion.getVersion());
        formatter.format("Build Date/Time: %s\n", CasVersion.getDateTime());
        formatter.format("Java Home: %s\n", properties.get("java.home"));
        formatter.format("Java Vendor: %s\n", properties.get("java.vendor"));
        formatter.format("Java Version: %s\n", properties.get("java.version"));
        formatter.format("OS Architecture: %s\n", properties.get("os.arch"));
        formatter.format("OS Name: %s\n", properties.get("os.name"));
        formatter.format("OS Version: %s\n", properties.get("os.version"));
        formatter.format("*******************************************************\n");
        return formatter.toString();
    }
}

70. SimpleCacheStatistics#toString()

Project: cas
File: SimpleCacheStatistics.java
@Override
public void toString(final StringBuilder builder) {
    if (this.name != null) {
        builder.append(this.name).append(':');
    }
    try (final Formatter formatter = new Formatter(builder)) {
        formatter.format("%.2f", this.size / BYTES_PER_MB);
        builder.append("MB used, ");
        builder.append(getPercentFree()).append("% free, ");
        builder.append(this.evictions).append(" evictions");
    }
}

71. AppendableLogRecord#appendFormattedMessage()

Project: buck
File: AppendableLogRecord.java
public void appendFormattedMessage(StringBuilder sb) {
    try (Formatter f = new Formatter(sb, Locale.US)) {
        f.format(getMessage(), getParameters());
    } catch (IllegalFormatException e) {
        sb.append("Invalid format string: ");
        sb.append(displayLevel);
        sb.append(" '");
        sb.append(getMessage());
        sb.append("' ");
        sb.append(Arrays.asList(getParameters()).toString());
    } catch (ConcurrentModificationException originalException) {
        throw new ConcurrentModificationException("Concurrent modification when logging for message " + getMessage(), originalException);
    }
}

72. Statsd#delta()

Project: btrace
File: Statsd.java
private void delta(String name, long value, double sampleRate, String tags) {
    StringBuilder sb = new StringBuilder(name);
    Formatter fmt = new Formatter(sb);
    sb.append(':');
    if (value > 0) {
        sb.append('+');
    } else if (value < 0) {
        sb.append('-');
    }
    sb.append(value).append('|').append('g');
    appendSampleRate(sampleRate, sb, fmt);
    appendTags(tags, sb);
    q.offer(sb.toString());
}

73. WorkspaceTest#config()

Project: bnd
File: WorkspaceTest.java
void config(Map<String, String> override) throws Exception {
    Map<String, String> config = new HashMap<>();
    config.put("local", tmpName + "/local");
    config.put("index", tmpName + "/index");
    config.put("releaseUrl", fnx.getBaseURI() + "/repo/");
    if (override != null)
        config.putAll(override);
    try (Formatter sb = new Formatter()) {
        sb.format("-plugin.maven= \\\n");
        sb.format("  %s; \\\n", MavenBndRepository.class.getName());
        sb.format("  name=test; \\\n", MavenBndRepository.class.getName());
        sb.format("  local=%s; \\\n", config.get("local"));
        sb.format("  releaseUrl=%s; \\\n", config.get("releaseUrl"));
        sb.format("  index=%s\n", config.get("index"));
        build.getParentFile().mkdirs();
        IO.store(sb.toString(), build);
        workspace = Workspace.getWorkspace(build.getParentFile().getParentFile());
        repo = workspace.getPlugin(MavenBndRepository.class);
    }
}

74. Platform#toString()

Project: bnd
File: Platform.java
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb);
    try {
        formatter.format("Name                %s%n", getName());
        formatter.format("Local               %s%n", getLocal());
        formatter.format("Global              %s%n", getGlobal());
        return formatter.toString();
    } finally {
        formatter.close();
    }
}

75. JustAnotherPackageManager#listSupportFiles()

Project: bnd
File: JustAnotherPackageManager.java
private String listSupportFiles(List<File> toDelete) throws Exception {
    Formatter f = new Formatter();
    try {
        if (toDelete == null) {
            toDelete = new ArrayList<File>();
        }
        int precount = toDelete.size();
        File confFile = IO.getFile(platform.getConfigFile()).getCanonicalFile();
        if (confFile.exists()) {
            f.format("    * %s \t0 Config file%n", confFile);
            toDelete.add(confFile);
        }
        String result = (toDelete.size() > precount) ? f.toString() : null;
        return result;
    } finally {
        f.close();
    }
}

76. VersionRange#toFilter()

Project: bnd
File: VersionRange.java
/**
	 * Convert to an OSGi filter expression
	 * 
	 */
public String toFilter() {
    Formatter f = new Formatter();
    try {
        if (high == Version.HIGHEST)
            return "(version>=" + low + ")";
        if (isRange()) {
            f.format("(&");
            if (includeLow())
                f.format("(version>=%s)", getLow());
            else
                f.format("(!(version<=%s))", getLow());
            if (includeHigh())
                f.format("(version<=%s)", getHigh());
            else
                f.format("(!(version>=%s))", getHigh());
            f.format(")");
        } else {
            f.format("(version>=%s)", getLow());
        }
        return f.toString();
    } finally {
        f.close();
    }
}

77. OBRFragment#filter()

Project: bnd
File: OBRFragment.java
// TODO finish
private static String filter(String ns, String primary, Map<String, String> value) {
    Formatter f = new Formatter();
    try {
        f.format("(&(%s=%s)", ns, primary);
        for (String key : value.keySet()) {
            if (key.equals("version") || key.equals("bundle-version")) {
                VersionRange vr = new VersionRange(value.get(key));
            } else {
                f.format("(%s=%s)", key, value.get(key));
            }
        }
        f.format(")");
    } finally {
        f.close();
    }
    return null;
}

78. PackageInfo#getContent()

Project: bnd
File: PackageInfo.java
/*
	 * Calculate the new content for a package info file.
	 */
private String getContent(boolean modern, String packageName, Version version) {
    Formatter f = new Formatter();
    try {
        if (modern) {
            f.format("@Version(\"%s\")\n", version);
            f.format("package %s;\n", packageName);
            f.format("import %s;\n", getVersionAnnotation());
        } else {
            f.format("version %s\n", version);
        }
        return f.toString();
    } finally {
        f.close();
    }
}

79. JustifTest#testSimple()

Project: bnd
File: JustifTest.java
public void testSimple() throws Exception {
    StringBuilder sb = new StringBuilder();
    Formatter f = new Formatter(sb);
    try {
        Justif j = new Justif(40, 4, 8);
        f.format("0123456789012345\nxx\t0-\t1can\n" + "           use instead of including individual modules in your project. Note:\n" + "           It does not include the Jiffle scripting language or Jiffle image\n" + "           operator.");
        f.flush();
        j.wrap(sb);
        System.out.println(sb);
    } finally {
        f.close();
    }
}

80. Data#details()

Project: bnd
File: Data.java
public static void details(Object data, Appendable out) throws Exception {
    Field fields[] = data.getClass().getFields();
    Formatter formatter = new Formatter(out);
    try {
        for (Field f : fields) {
            String name = f.getName();
            name = Character.toUpperCase(name.charAt(0)) + name.substring(1);
            Object object = f.get(data);
            if (object != null && object.getClass() == byte[].class)
                object = Hex.toHexString((byte[]) object);
            else if (object != null && object.getClass().isArray())
                object = Converter.cnv(List.class, object);
            formatter.format("%-40s %s%n", name, object);
        }
    } finally {
        formatter.close();
    }
}

81. Song#getDuration()

Project: android-xbmcremote
File: Song.java
/**
	 * Returns a formatted string (MM:SS) for a number of seconds.
	 * @param d Number of seconds
	 * @return Formatted time
	 */
public static String getDuration(int d) {
    StringBuilder sb = new StringBuilder();
    if (d > 3600) {
        sb.append((int) d / 3600);
        sb.append(":");
        d %= 3600;
    }
    int min = (int) d / 60;
    Formatter f = new Formatter();
    if (sb.length() > 0) {
        //			sb.append(f.format("%02d", min));
        if (min < 10)
            sb.append(0);
        sb.append(min);
        sb.append(":");
    } else {
        sb.append(min + ":");
    }
    d %= 60;
    sb.append(f.format("%02d", d));
    return sb.toString();
}

82. FormatIndexing#main()

Project: checker-framework
File: FormatIndexing.java
public static void main(String... p) {
    Formatter f = new Formatter();
    // GENERAL and self intersections
    @Format({ ConversionCategory.CHAR }) String ccc = "%1$c %<c %c";
    @Format({ ConversionCategory.CHAR }) String c = "%c %<s";
    @Format({ ConversionCategory.INT }) String i = "%d %<s";
    @Format({ ConversionCategory.FLOAT }) String d = "%f %<s";
    @Format({ ConversionCategory.TIME }) String t = "%TT %<s";
    // test CHAR_AND_INT
    @Format({ ConversionCategory.CHAR_AND_INT }) String ici = "%1$d %1$c";
    f.format("%1$c %1$d", (int) 42);
    f.format("%1$c %1$d %1$d", (int) 42);
    //:: error: (argument.type.incompatible)
    f.format("%1$c %1$d", (long) 42);
    //:: error: (argument.type.incompatible)
    f.format("%1$c %1$d", 'c');
    // test INT_AND_TIME
    @Format({ ConversionCategory.INT_AND_TIME }) String iit = "%1$tT %1$d";
    f.format("%1$tT %1$d", (long) 42);
    f.format("%1$d %1$tT %1$d", (long) 42);
    //:: error: (argument.type.incompatible)
    f.format("%1$tT %1$d", (int) 42);
    //:: error: (argument.type.incompatible)
    f.format("%1$tT %1$d", new Date());
    // test NULL
    @Format({ ConversionCategory.NULL }) String cf = "%c %<f";
    @Format({ ConversionCategory.NULL }) String ct = "%c %<TT";
    @Format({ ConversionCategory.NULL }) String _if = "%d %<f";
    @Format({ ConversionCategory.NULL }) String fc = "%f %<c";
    @Format({ ConversionCategory.NULL }) String fi = "%f %<d";
    @Format({ ConversionCategory.NULL }) String ft = "%f %<TT";
    @Format({ ConversionCategory.NULL }) String tc = "%TT %<c";
    @Format({ ConversionCategory.NULL, ConversionCategory.INT }) String tf = "%TT %<f %2$d";
    @Format({ ConversionCategory.NULL }) String icf = "%d %<c %<f";
    @Format({ ConversionCategory.NULL }) String itc = "%d %<TT %<c";
    //:: error: (format.specifier.null)
    f.format(tf, null, 0);
    //:: warning: (format.indirect.arguments) :: error: (format.specifier.null)
    f.format(tf, (Object[]) null);
    //:: error: (format.specifier.null)
    f.format(tf, 'c', 0);
    //:: error: (format.specifier.null)
    f.format(tf, (Object) null, 0);
    // test UNUSED
    //:: warning: (format.argument.unused)
    f.format("%1$s %3$s", "Hello", "Missing", "World");
    //:: warning: (format.argument.unused) :: warning: (format.indirect.arguments)
    f.format("%1$s %3$s", new Object[5]);
    //:: warning: (format.argument.unused) :: warning: (format.indirect.arguments)
    f.format("%5$s", (Object[]) null);
    //:: warning: (format.argument.unused)
    f.format("%3$s", null, null, null);
    //:: warning: (format.argument.unused)
    f.format("%7$s %2$s %4$s %<s %7$s", 0, 0, 0, 0, 0, 0, 0);
    f.close();
    // test UNUSED and NULL
    //:: warning: (format.argument.unused) :: error: (format.specifier.null)
    f.format("%1$s %3$d %3$f", "Hello", "Missing", "World");
}

83. DebugMultipleProvidersAppStartupTest#testLogOneProvider()

Project: wink
File: DebugMultipleProvidersAppStartupTest.java
/**
     * Tests that a Provider is logged at the debug level.
     */
public void testLogOneProvider() throws Exception {
    List<LogRecord> records = handler.getRecords();
    /*
         * This is actually a deterministic order for this particular test. The
         * type of provider and the media type determine the order. In
         * situations where there are no order (i.e. application/json versus
         * application/custom), the test will be fairly random.
         */
    final String provider1Message = "The class org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyEntityReader was registered as a JAX-RS MessageBodyReader provider for java.lang.String Java types and custom2/type2 media types.";
    assertEquals(provider1Message, records.get(11).getMessage());
    assertEquals(Level.INFO, records.get(11).getLevel());
    final String provider2Message = "The class org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyEntityReader was registered as a JAX-RS MessageBodyReader provider for java.lang.String Java types and custom/* media types.";
    assertEquals(provider2Message, records.get(12).getMessage());
    assertEquals(Level.INFO, records.get(12).getLevel());
    final String provider3Message = "The class org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyEntityProvider was registered as a JAX-RS MessageBodyReader provider for all Java types and */* media types.";
    assertEquals(provider3Message, records.get(13).getMessage());
    assertEquals(Level.INFO, records.get(13).getLevel());
    final String provider4Message = "The class org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyEntityProvider was registered as a JAX-RS MessageBodyWriter provider for all Java types and text/plain media types.";
    assertEquals(provider4Message, records.get(14).getMessage());
    assertEquals(Level.INFO, records.get(14).getLevel());
    final String provider5Message = "The class org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyExceptionMapper was registered as a JAX-RS ExceptionMapper provider for java.lang.NullPointerException Java types.";
    assertEquals(provider5Message, records.get(15).getMessage());
    assertEquals(Level.INFO, records.get(15).getLevel());
    final String provider6Message = "The class org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyContextResolver was registered as a JAX-RS ContextResolver provider for java.lang.String Java types and */* media types.";
    assertEquals(provider6Message, records.get(16).getMessage());
    assertEquals(Level.INFO, records.get(16).getLevel());
    assertEquals(Level.FINE, records.get(17).getLevel());
    StringBuffer sb = new StringBuffer();
    Formatter f = new Formatter(sb);
    f.format("The following JAX-RS MessageBodyReader providers are registered:");
    f.format("%n%1$-35s %2$-25s %3$-8s %4$s", "Consumes Media Type", "Generic Type", "Custom?", "Provider Class");
    f.format("%n%1$-35s %2$-25s %3$-8s %4$s", "custom2/type2", "String", "true", "org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyEntityReader");
    f.format("%n%1$-35s %2$-25s %3$-8s %4$s", "custom/*", "String", "true", "org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyEntityReader");
    f.format("%n%1$-35s %2$-25s %3$-8s %4$s", "*/*", "Object", "true", "org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyEntityProvider");
    assertEquals(sb.toString(), records.get(17).getMessage());
    assertEquals(Level.FINE, records.get(18).getLevel());
    sb = new StringBuffer();
    f = new Formatter(sb);
    f.format("The following JAX-RS MessageBodyWriter providers are registered:");
    f.format("%n%1$-35s %2$-25s %3$-8s %4$s", "Produces Media Type", "Generic Type", "Custom?", "Provider Class");
    f.format("%n%1$-35s %2$-25s %3$-8s %4$s", "text/plain", "Object", "true", "org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyEntityProvider");
    assertEquals(sb.toString(), records.get(18).getMessage());
    assertEquals(Level.FINE, records.get(19).getLevel());
    sb = new StringBuffer();
    f = new Formatter(sb);
    f.format("The following JAX-RS ExceptionMapper providers are registered:");
    f.format("%n%1$-25s %2$-8s %3$s", "Generic Type", "Custom?", "Provider Class");
    f.format("%n%1$-25s %2$-8s %3$s", "NullPointerException", "true", "org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyExceptionMapper");
    assertEquals(sb.toString(), records.get(19).getMessage());
    assertEquals(Level.FINE, records.get(20).getLevel());
    sb = new StringBuffer();
    f = new Formatter(sb);
    f.format("The following JAX-RS ContextResolver providers are registered:");
    f.format("%n%1$-35s %2$-25s %3$-8s %4$s", "Produces Media Type", "Generic Type", "Custom?", "Provider Class");
    f.format("%n%1$-35s %2$-25s %3$-8s %4$s", "*/*", "String", "true", "org.apache.wink.server.serviceability.DebugMultipleProvidersAppStartupTest$MyContextResolver");
    assertEquals(sb.toString(), records.get(20).getMessage());
    assertEquals(21, records.size());
}

84. FormatBasic#main()

Project: checker-framework
File: FormatBasic.java
public static void main(String... p) {
    Formatter f = new Formatter();
    f.format("String");
    f.format("String %20% %n");
    f.format("%% %s", "str");
    f.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d");
    f.format("e = %+10.4f", Math.E);
    f.format("Amount gained or lost since last statement: $ %(,.2f", -6217.58);
    f.format("Local time: %tT", Calendar.getInstance());
    f.format("Unable to open file '%1$s': %2$s", "food", "No such file or directory");
    f.format("Duke's Birthday: %1$tm %1$te,%1$tY", new GregorianCalendar(1995, Calendar.MAY, 23));
    f.format("Duke's Birthday: %tm %<te,%<tY", new Date());
    f.format("Duke's Birthday: %2$tm %<te,%<tY (it's the %dth)", 123, new Date());
    String s = "%+s%";
    //:: error: (format.string.invalid)
    f.format(s, "illegal");
    //:: error: (format.string.invalid)
    f.format("%+s%", "illegal");
    //:: error: (format.string.invalid)
    f.format("Wrong < indexing: %1$tm %<te,%<$tY", new Date());
    //:: error: (format.string.invalid)
    f.format("%t", new Date());
    //:: error: (argument.type.incompatible)
    f.format("%Td", (int) 231);
    f.close();
}

85. ConversionNull#main()

Project: checker-framework
File: ConversionNull.java
public static void main(String... p) {
    Formatter f = new Formatter();
    f.format("%d %s", 0, null);
    f.format("%s", (Object) null);
    //:: error: (argument.type.incompatible)
    f.format("%d %c", 0, null);
    f.format("%c", (Character) null);
    //:: error: (argument.type.incompatible)
    f.format("%c", (Object) null);
    //:: error: (argument.type.incompatible)
    f.format("%d %d", 0, null);
    f.format("%d", (Integer) null);
    //:: error: (argument.type.incompatible)
    f.format("%d", (Object) null);
    //:: error: (argument.type.incompatible)
    f.format("%d %f", 0, null);
    f.format("%f", (Float) null);
    //:: error: (argument.type.incompatible)
    f.format("%f", (Object) null);
    //:: error: (argument.type.incompatible)
    f.format("%d %tD", 0, null);
    f.format("%tD", (Date) null);
    //:: error: (argument.type.incompatible)
    f.format("%tD", (Object) null);
    System.out.println(f.toString());
    f.close();
}

86. EhcacheBasicRemoveAllTest#dumpResults()

Project: ehcache3
File: EhcacheBasicRemoveAllTest.java
/**
   * Writes a dump of test object details to {@code System.out} if, and only if, {@link #debugResults} is enabled.
   *
   * @param fakeStore the {@link org.ehcache.core.EhcacheBasicCrudBase.FakeStore FakeStore} instance used in the test
   * @param originalStoreContent  the original content provided to {@code fakeStore}
   * @param fakeLoaderWriter the {@link org.ehcache.core.EhcacheBasicCrudBase.FakeCacheLoaderWriter FakeCacheLoaderWriter} instances used in the test
   * @param originalWriterContent the original content provided to {@code fakeLoaderWriter}
   * @param contentUpdates the {@code Set} provided to the {@link EhcacheWithLoaderWriter#removeAll(java.util.Set)} call in the test
   * @param expectedFailures the {@code Set} of failing keys expected for the test
   * @param expectedSuccesses the {@code Set} of successful keys expected for the test
   * @param bcweSuccesses the {@code Set} from {@link BulkCacheWritingException#getSuccesses()}
   * @param bcweFailures the {@code Map} from {@link BulkCacheWritingException#getFailures()}
   */
private void dumpResults(final FakeStore fakeStore, final Map<String, String> originalStoreContent, final FakeCacheLoaderWriter fakeLoaderWriter, final Map<String, String> originalWriterContent, final Set<String> contentUpdates, final Set<String> expectedFailures, final Set<String> expectedSuccesses, final Set<String> bcweSuccesses, final Map<String, Exception> bcweFailures) {
    if (!debugResults) {
        return;
    }
    final StringBuilder sb = new StringBuilder(2048);
    final Formatter fmt = new Formatter(sb);
    fmt.format("Dumping results of %s:%n", this.name.getMethodName());
    fmt.format("    Content Update Keys: %s%n", sort(contentUpdates));
    fmt.format("    Original Store Keys : %s%n", sort(originalStoreContent.keySet()));
    fmt.format("    Final Store Keys    : %s%n", sort(fakeStore.getEntryMap().keySet()));
    fmt.format("    Original Writer Keys: %s%n", sort(originalWriterContent.keySet()));
    fmt.format("    Final Writer Keys   : %s%n", sort(fakeLoaderWriter.getEntryMap().keySet()));
    fmt.format("    Expected Successes: %s%n", sort(expectedSuccesses));
    fmt.format("    Declared Successes: %s%n", sort(bcweSuccesses));
    fmt.format("    Expected Failures: %s%n", sort(expectedFailures));
    fmt.format("    Declared Failures: %s%n", sort(bcweFailures.keySet()));
    System.err.flush();
    System.out.append(sb);
    System.out.flush();
}

87. EhcacheBasicPutAllTest#dumpResults()

Project: ehcache3
File: EhcacheBasicPutAllTest.java
/**
   * Writes a dump of test object details to {@code System.out} if, and only if, {@link #debugResults} is enabled.
   *
   * @param fakeStore the {@link org.ehcache.core.EhcacheBasicCrudBase.FakeStore FakeStore} instance used in the test
   * @param originalStoreContent  the original content provided to {@code fakeStore}
   * @param fakeLoaderWriter the {@link org.ehcache.core.EhcacheBasicCrudBase.FakeCacheLoaderWriter FakeCacheLoaderWriter} instances used in the test
   * @param originalWriterContent the original content provided to {@code fakeLoaderWriter}
   * @param contentUpdates the {@code Map} provided to the {@link EhcacheWithLoaderWriter#putAll(java.util.Map)} call in the test
   * @param expectedFailures the {@code Set} of failing keys expected for the test
   * @param expectedSuccesses the {@code Set} of successful keys expected for the test
   * @param bcweSuccesses the {@code Set} from {@link BulkCacheWritingException#getSuccesses()}
   * @param bcweFailures the {@code Map} from {@link BulkCacheWritingException#getFailures()}
   */
private void dumpResults(final FakeStore fakeStore, final Map<String, String> originalStoreContent, final FakeCacheLoaderWriter fakeLoaderWriter, final Map<String, String> originalWriterContent, final Map<String, String> contentUpdates, final Set<String> expectedFailures, final Map<String, String> expectedSuccesses, final Set<String> bcweSuccesses, final Map<String, Exception> bcweFailures) {
    if (!debugResults) {
        return;
    }
    final StringBuilder sb = new StringBuilder(2048);
    final Formatter fmt = new Formatter(sb);
    fmt.format("Dumping results of %s:%n", this.name.getMethodName());
    fmt.format("    Content Update Entries: %s%n", sortMap(contentUpdates));
    fmt.format("    Original Store Entries : %s%n", sortMap(originalStoreContent));
    fmt.format("    Final Store Entries    : %s%n", sortMap(fakeStore.getEntryMap()));
    fmt.format("    Original Writer Entries: %s%n", sortMap(originalWriterContent));
    fmt.format("    Final Writer Entries   : %s%n", sortMap(fakeLoaderWriter.getEntryMap()));
    fmt.format("    Expected Successes: %s%n", sort(expectedSuccesses.keySet()));
    fmt.format("    Declared Successes: %s%n", sort(bcweSuccesses));
    fmt.format("    Expected Failures: %s%n", sort(expectedFailures));
    fmt.format("    Declared Failures: %s%n", sort(bcweFailures.keySet()));
    System.err.flush();
    System.out.append(sb);
    System.out.flush();
}

88. Flow#main()

Project: checker-framework
File: Flow.java
public static void main(String... p) {
    Formatter f = new Formatter();
    String unqual = System.lineSeparator();
    String qual = "%s %d %f";
    String wrong = "%$s";
    callUnqual("%s");
    callUnqual(qual);
    callUnqual(wrong);
    callUnqual(null);
    //:: error: (format.string.invalid)
    f.format(null);
    @Format({ ConversionCategory.GENERAL }) String nullAssign = null;
    //:: error: (format.string.invalid)
    f.format(nullAssign, "string");
    if (false) {
        nullAssign = "%s";
    }
    f.format(nullAssign, "string");
    //:: error: (assignment.type.incompatible)
    @Format({ ConversionCategory.GENERAL }) String err0 = unqual;
    //:: error: (assignment.type.incompatible)
    @Format({ ConversionCategory.GENERAL }) String err2 = "%$s";
    @Format({ ConversionCategory.GENERAL }) String ok = "%s";
    String u = "%s" + " %" + "d";
    String v = FormatUtil.asFormat(u, ConversionCategory.GENERAL, ConversionCategory.INT);
    f.format(u, "String", 1337);
    //:: error: (argument.type.incompatible)
    f.format(u, "String", 7.4);
    try {
        String l = FormatUtil.asFormat(u, ConversionCategory.FLOAT, ConversionCategory.INT);
        Assert.fail("Expected Exception");
    } catch (Error e) {
    }
    String a = "Success: %s %d %f";
    f.format(a, "String", 1337, 7.5);
    String b = "Fail: %d";
    //:: error: (argument.type.incompatible)
    f.format(b, "Wrong");
    @Format({ ConversionCategory.GENERAL, ConversionCategory.INT, ConversionCategory.FLOAT, ConversionCategory.CHAR }) String s = "Success: %s %d %f %c";
    f.format(s, "OK", 42, 3.14, 'c');
    @Format({ ConversionCategory.GENERAL, ConversionCategory.INT, ConversionCategory.FLOAT }) String t = "Fail: %s %d %f";
    //:: error: (argument.type.incompatible)
    f.format(t, "OK", "Wrong", 3.14);
    call(f, "Success: %tM");
    //:: error: (argument.type.incompatible)
    call(f, "Fail: %d");
    System.out.println(f.toString());
    f.close();
}

89. PerformanceTest#testBenches()

Project: exp4j
File: PerformanceTest.java
@Test
public void testBenches() throws Exception {
    StringBuffer sb = new StringBuffer();
    Formatter fmt = new Formatter(sb);
    fmt.format("+------------------------+---------------------------+--------------------------+%n");
    fmt.format("| %-22s | %-25s | %-24s |%n", "Implementation", "Calculations per Second", "Percentage of Math");
    fmt.format("+------------------------+---------------------------+--------------------------+%n");
    System.out.print(sb.toString());
    sb.setLength(0);
    int math = benchJavaMath();
    double mathRate = (double) math / (double) BENCH_TIME;
    fmt.format("| %-22s | %25.2f | %22.2f %% |%n", "Java Math", mathRate, 100f);
    System.out.print(sb.toString());
    sb.setLength(0);
    int db = benchDouble();
    double dbRate = (double) db / (double) BENCH_TIME;
    fmt.format("| %-22s | %25.2f | %22.2f %% |%n", "exp4j", dbRate, dbRate * 100 / mathRate);
    System.out.print(sb.toString());
    sb.setLength(0);
    int js = benchJavaScript();
    double jsRate = (double) js / (double) BENCH_TIME;
    fmt.format("| %-22s | %25.2f | %22.2f %% |%n", "JSR-223 (Java Script)", jsRate, jsRate * 100 / mathRate);
    fmt.format("+------------------------+---------------------------+--------------------------+%n");
    System.out.print(sb.toString());
}

90. DebugMultipleResourcesAppStartupTest#testLogNoResource()

Project: wink
File: DebugMultipleResourcesAppStartupTest.java
/**
     * Tests that the JAX-RS application sub-class init params is logged and
     * other debug startup.
     * 
     * @throws Exception
     */
public void testLogNoResource() throws Exception {
    List<LogRecord> records = handler.getRecords();
    assertEquals("Configuration Settings:", records.get(0).getMessage());
    assertEquals(Level.FINE, records.get(0).getLevel());
    assertEquals("Request User Handlers: []", records.get(1).getMessage());
    assertEquals(Level.FINE, records.get(1).getLevel());
    assertEquals("Response User Handlers: []", records.get(2).getMessage());
    assertEquals(Level.FINE, records.get(2).getLevel());
    assertEquals("Error User Handlers: []", records.get(3).getMessage());
    assertEquals(Level.FINE, records.get(3).getLevel());
    assertTrue(records.get(4).getMessage(), records.get(4).getMessage().startsWith("MediaTypeMapper: "));
    assertEquals(Level.FINE, records.get(4).getLevel());
    assertTrue(records.get(5).getMessage(), records.get(5).getMessage().startsWith("AlternateShortcutMap: "));
    assertEquals(Level.FINE, records.get(5).getLevel());
    assertTrue(records.get(6).getMessage(), records.get(6).getMessage().startsWith("Properties: "));
    assertEquals(Level.FINE, records.get(6).getLevel());
    assertEquals("HttpMethodOverrideHeaders: []", records.get(7).getMessage());
    assertEquals(Level.FINE, records.get(7).getLevel());
    assertEquals("The system is using the org.apache.wink.server.internal.servlet.MockServletInvocationTest$MockApplication JAX-RS application class that is named in the javax.ws.rs.Application init-param initialization parameter.", records.get(8).getMessage());
    assertEquals(Level.INFO, records.get(8).getLevel());
    assertEquals("The following JAX-RS application has been processed: org.apache.wink.server.internal.servlet.MockServletInvocationTest$MockApplication", records.get(9).getMessage());
    assertEquals(Level.INFO, records.get(9).getLevel());
    assertEquals("The server has registered the JAX-RS resource class org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource3 with @Path(/longpath/longpath/longpath).", records.get(10).getMessage());
    assertEquals(Level.INFO, records.get(10).getLevel());
    assertEquals("The server has registered the JAX-RS resource class org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource4 with @Path(/somepath).", records.get(11).getMessage());
    assertEquals(Level.INFO, records.get(11).getLevel());
    assertEquals("The server has registered the JAX-RS resource class org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource2 with @Path(/hello2).", records.get(12).getMessage());
    assertEquals(Level.INFO, records.get(12).getLevel());
    assertEquals("The server has registered the JAX-RS resource class org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource1 with @Path(/hello).", records.get(13).getMessage());
    assertEquals(Level.INFO, records.get(13).getLevel());
    StringBuffer resourceTable = new StringBuffer();
    Formatter f = new Formatter(resourceTable);
    f.format("Registered JAX-RS resources: %n%1$-80s %2$-13s %3$-20s %4$-20s %5$s", "Path", "HTTP Method", "Consumes", "Produces", "Resource Method");
    f.format("%n%1$-80s %2$-13s %3$-20s %4$-20s %5$s", "/longpath/longpath/longpath/sublocator", "(Sub-Locator)", "[*/*]", "[*/*]", "org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource3.get()");
    f.format("%n%1$-80s %2$-13s %3$-20s %4$-20s %5$s", "/somepath", "PUT", "[*/*]", "[*/*]", "org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource4.put(byte[])");
    f.format("%n%1$-80s %2$-13s %3$-20s %4$-20s %5$s", "/somepath/subresource", "POST", "[*/*]", "[*/*]", "org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource4.getSubresource(String)");
    f.format("%n%1$-80s %2$-13s %3$-20s %4$-20s %5$s", "/somepath/sublocator", "(Sub-Locator)", "[*/*]", "[*/*]", "org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource4.getSublocator(String)");
    f.format("%n%1$-80s %2$-13s %3$-20s %4$-20s %5$s", "/hello2/subpath", "DELETE", "[*/*]", "[*/*]", "org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource2.get()");
    f.format("%n%1$-80s %2$-13s %3$-20s %4$-20s %5$s", "/hello", "GET", "[*/*]", "[*/*]", "org.apache.wink.server.serviceability.DebugMultipleResourcesAppStartupTest$MyResource1.get()");
    assertEquals(resourceTable.toString(), records.get(14).getMessage());
    assertEquals(Level.FINE, records.get(14).getLevel());
    assertEquals("There are no custom JAX-RS providers defined in the application.", records.get(15).getMessage());
    assertEquals(Level.INFO, records.get(15).getLevel());
    assertEquals(16, records.size());
}

91. DebugSimpleResponseTest#testResponseHeadersOutput()

Project: wink
File: DebugSimpleResponseTest.java
/**
     * Tests that a response header is sent and output in the log.
     */
public void testResponseHeadersOutput() throws Exception {
    handler.getRecords().clear();
    List<LogRecord> records = handler.getRecords();
    MockHttpServletRequest request = MockRequestConstructor.constructMockRequest("GET", "/abcd/responseWithHeaders", MediaType.WILDCARD);
    MockHttpServletResponse response = invoke(request);
    assertEquals(200, response.getStatus());
    assertEquals("", response.getContentAsString());
    int responseEntityNotWritten = 0;
    int responseEntityContentAsStringMsgCount = 0;
    int countNumMessagesFromResponsesHandler = 0;
    int countHeadersMessage = 0;
    StringBuilder headersOutput = new StringBuilder();
    Formatter f = new Formatter(headersOutput);
    f.format("The written response headers:");
    f.format("%n%1$-30s%2$s", "Content-Encoding", "gzip");
    f.format("%n%1$-30s%2$s", "Cookie", "abcd");
    f.format("%n%1$-30s%2$s", "Set-Cookie", "lmnop");
    f.format("%n%1$-30s%2$s", "Set-Cookie", "abcd");
    f.format("%n%1$-30s%2$s", "WWW-Authenticate", "realm=something");
    for (LogRecord record : records) {
        if ("The response entity was not written to the HttpServletResponse.getOutputStream().".equals(record.getMessage())) {
            ++responseEntityNotWritten;
            assertEquals(Level.FINE, record.getLevel());
        }
        if ("".equals(record.getMessage())) {
            ++responseEntityContentAsStringMsgCount;
            assertEquals(Level.FINE, record.getLevel());
        }
        if (record.getLoggerName().equals((Responses.class.getName()))) {
            ++countNumMessagesFromResponsesHandler;
        }
        if (headersOutput.toString().equals(record.getMessage())) {
            ++countHeadersMessage;
            assertEquals(Level.FINE, record.getLevel());
        }
    }
    assertEquals(1, responseEntityNotWritten);
    assertEquals(0, responseEntityContentAsStringMsgCount);
    assertEquals(1, countHeadersMessage);
    assertEquals(2, countNumMessagesFromResponsesHandler);
}

92. RecordUsageAnalyser#toString()

Project: jackrabbit-oak
File: RecordUsageAnalyser.java
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    @SuppressWarnings("resource") Formatter formatter = new Formatter(sb);
    formatter.format("%s in maps (%s leaf and branch records)%n", byteCountToDisplaySize(mapSize), mapCount);
    formatter.format("%s in lists (%s list and bucket records)%n", byteCountToDisplaySize(listSize), listCount);
    formatter.format("%s in values (value and block records of %s properties, " + "%s/%s/%s/%s small/medium/long/external blobs, %s/%s/%s small/medium/long strings)%n", byteCountToDisplaySize(valueSize), propertyCount, smallBlobCount, mediumBlobCount, longBlobCount, externalBlobCount, smallStringCount, mediumStringCount, longStringCount);
    formatter.format("%s in templates (%s template records)%n", byteCountToDisplaySize(templateSize), templateCount);
    formatter.format("%s in nodes (%s node records)%n", byteCountToDisplaySize(nodeSize), nodeCount);
    formatter.format("links to non existing segments: %s", deadLinks);
    return sb.toString();
}

93. RecordUsageAnalyser#toString()

Project: jackrabbit-oak
File: RecordUsageAnalyser.java
@Override
public String toString() {
    StringBuilder sb = new StringBuilder();
    @SuppressWarnings("resource") Formatter formatter = new Formatter(sb);
    formatter.format("%s in maps (%s leaf and branch records)%n", byteCountToDisplaySize(mapSize), mapCount);
    formatter.format("%s in lists (%s list and bucket records)%n", byteCountToDisplaySize(listSize), listCount);
    formatter.format("%s in values (value and block records of %s properties, " + "%s/%s/%s/%s small/medium/long/external blobs, %s/%s/%s small/medium/long strings)%n", byteCountToDisplaySize(valueSize), propertyCount, smallBlobCount, mediumBlobCount, longBlobCount, externalBlobCount, smallStringCount, mediumStringCount, longStringCount);
    formatter.format("%s in templates (%s template records)%n", byteCountToDisplaySize(templateSize), templateCount);
    formatter.format("%s in nodes (%s node records)%n", byteCountToDisplaySize(nodeSize), nodeCount);
    formatter.format("links to non existing segments: %s", deadLinks);
    return sb.toString();
}

94. FormatMethods#main()

Project: checker-framework
File: FormatMethods.java
public static void main(String... p) {
    Formatter f = new Formatter();
    f.format("%d", 1337);
    f.format(Locale.GERMAN, "%d", 1337);
    //:: error: (argument.type.incompatible)
    f.format("%f", 1337);
    //:: error: (argument.type.incompatible)
    f.format(Locale.GERMAN, "%f", 1337);
    f.close();
    String.format("%d", 1337);
    String.format(Locale.GERMAN, "%d", 1337);
    //:: error: (argument.type.incompatible)
    String.format("%f", 1337);
    //:: error: (argument.type.incompatible)
    String.format(Locale.GERMAN, "%f", 1337);
    PrintWriter pw = new PrintWriter(new ByteArrayOutputStream());
    pw.format("%d", 1337);
    pw.format(Locale.GERMAN, "%d", 1337);
    pw.printf("%d", 1337);
    pw.printf(Locale.GERMAN, "%d", 1337);
    //:: error: (argument.type.incompatible)
    pw.format("%f", 1337);
    //:: error: (argument.type.incompatible)
    pw.format(Locale.GERMAN, "%f", 1337);
    //:: error: (argument.type.incompatible)
    pw.printf("%f", 1337);
    //:: error: (argument.type.incompatible)
    pw.printf(Locale.GERMAN, "%f", 1337);
    pw.close();
    PrintStream ps = System.out;
    ps.format("%d", 1337);
    ps.format(Locale.GERMAN, "%d", 1337);
    ps.printf("%d", 1337);
    ps.printf(Locale.GERMAN, "%d", 1337);
    //:: error: (argument.type.incompatible)
    ps.format("%f", 1337);
    //:: error: (argument.type.incompatible)
    ps.format(Locale.GERMAN, "%f", 1337);
    //:: error: (argument.type.incompatible)
    ps.printf("%f", 1337);
    //:: error: (argument.type.incompatible)
    ps.printf(Locale.GERMAN, "%f", 1337);
    ps.close();
    Console c = System.console();
    c.format("%d", 1337);
    c.printf("%d", 1337);
    //:: error: (argument.type.incompatible)
    c.format("%f", 1337);
    //:: error: (argument.type.incompatible)
    c.printf("%f", 1337);
}

95. JustAnotherPackageManager#listFiles()

Project: bnd
File: JustAnotherPackageManager.java
private String listFiles(final File cache, List<File> toDelete) throws Exception {
    boolean stopServices = false;
    if (toDelete == null) {
        toDelete = new ArrayList<File>();
    } else {
        stopServices = true;
    }
    int count = 0;
    Formatter f = new Formatter();
    f.format(" - Cache:%n    * %s%n", cache.getCanonicalPath());
    f.format(" - Commands:%n");
    for (CommandData cdata : getCommands(new File(cache, COMMANDS))) {
        f.format("    * %s \t0 handle for \"%s\"%n", cdata.bin, cdata.name);
        toDelete.add(new File(cdata.bin));
        count++;
    }
    f.format(" - Services:%n");
    for (ServiceData sdata : getServices(new File(cache, SERVICE))) {
        if (sdata != null) {
            f.format("    * %s \t0 service directory for \"%s\"%n", sdata.sdir, sdata.name);
            toDelete.add(new File(sdata.sdir));
            File initd = platform.getInitd(sdata);
            if (initd != null && initd.exists()) {
                f.format("    * %s \t0 init.d file for \"%s\"%n", initd.getCanonicalPath(), sdata.name);
                toDelete.add(initd);
            }
            if (stopServices) {
                Service s = getService(sdata);
                try {
                    s.stop();
                } catch (Exception e) {
                }
            }
            count++;
        }
    }
    f.format("%n");
    String result = (count > 0) ? f.toString() : null;
    f.close();
    return result;
}

96. FTPFile#toFormattedString()

Project: commons-net
File: FTPFile.java
/**
     * Returns a string representation of the FTPFile information.
     * This currently mimics the Unix listing format.
     * This method allows the Calendar time zone to be overridden.
     * <p>
     * Note: if the instance is not valid {@link #isValid()}, no useful
     * information can be returned. In this case, use {@link #getRawListing()}
     * instead.
     * @param timezone the timezone to use for displaying the time stamp
     * If {@code null}, then use the Calendar entry timezone
     * @return A string representation of the FTPFile information.
     * @since 3.4
     */
public String toFormattedString(final String timezone) {
    if (!isValid()) {
        return "[Invalid: could not parse file entry]";
    }
    StringBuilder sb = new StringBuilder();
    Formatter fmt = new Formatter(sb);
    sb.append(formatType());
    sb.append(permissionToString(USER_ACCESS));
    sb.append(permissionToString(GROUP_ACCESS));
    sb.append(permissionToString(WORLD_ACCESS));
    fmt.format(" %4d", Integer.valueOf(getHardLinkCount()));
    fmt.format(" %-8s %-8s", getUser(), getGroup());
    fmt.format(" %8d", Long.valueOf(getSize()));
    Calendar timestamp = getTimestamp();
    if (timestamp != null) {
        if (timezone != null) {
            TimeZone newZone = TimeZone.getTimeZone(timezone);
            if (!newZone.equals(timestamp.getTimeZone())) {
                Date original = timestamp.getTime();
                Calendar newStamp = Calendar.getInstance(newZone);
                newStamp.setTime(original);
                timestamp = newStamp;
            }
        }
        fmt.format(" %1$tY-%1$tm-%1$td", timestamp);
        // Only display time units if they are present
        if (timestamp.isSet(Calendar.HOUR_OF_DAY)) {
            fmt.format(" %1$tH", timestamp);
            if (timestamp.isSet(Calendar.MINUTE)) {
                fmt.format(":%1$tM", timestamp);
                if (timestamp.isSet(Calendar.SECOND)) {
                    fmt.format(":%1$tS", timestamp);
                    if (timestamp.isSet(Calendar.MILLISECOND)) {
                        fmt.format(".%1$tL", timestamp);
                    }
                }
            }
            fmt.format(" %1$tZ", timestamp);
        }
    }
    sb.append(' ');
    sb.append(getName());
    fmt.close();
    return sb.toString();
}

97. TapestryAppInitializer#announceStartup()

Project: tapestry-5
File: TapestryAppInitializer.java
/**
     * Announce application startup, by logging (at INFO level) the names of all pages,
     * components, mixins and services.
     */
public void announceStartup() {
    if (// if info logging is off we can stop now
    !logger.isInfoEnabled()) {
        return;
    }
    long toFinish = System.currentTimeMillis();
    SymbolSource source = registry.getService("SymbolSource", SymbolSource.class);
    StringBuilder buffer = new StringBuilder("Startup status:\n\nServices:\n\n");
    Formatter f = new Formatter(buffer);
    int unrealized = 0;
    ServiceActivityScoreboard scoreboard = registry.getService(ServiceActivityScoreboard.class);
    List<ServiceActivity> serviceActivity = scoreboard.getServiceActivity();
    int longest = 0;
    for (ServiceActivity activity : serviceActivity) {
        Status status = activity.getStatus();
        longest = Math.max(longest, activity.getServiceId().length());
        if (status == Status.DEFINED || status == Status.VIRTUAL)
            unrealized++;
    }
    String formatString = "%" + longest + "s: %s\n";
    for (ServiceActivity activity : serviceActivity) {
        f.format(formatString, activity.getServiceId(), activity.getStatus().name());
    }
    f.format("\n%4.2f%% unrealized services (%d/%d)\n", 100. * unrealized / serviceActivity.size(), unrealized, serviceActivity.size());
    f.format("\nApplication '%s' (version %s) startup time: %,d ms to build IoC Registry, %,d ms overall.", appName, source.valueForSymbol(SymbolConstants.APPLICATION_VERSION), registryCreatedTime - startTime, toFinish - startTime);
    String version = source.valueForSymbol(SymbolConstants.TAPESTRY_VERSION);
    boolean productionMode = Boolean.parseBoolean(source.valueForSymbol(SymbolConstants.PRODUCTION_MODE));
    buffer.append("\n\n");
    buffer.append(" ______                  __             ____\n");
    buffer.append("/_  __/__ ____  ___ ___ / /_______ __  / __/\n");
    buffer.append(" / / / _ `/ _ \\/ -_|_-</ __/ __/ // / /__ \\ \n");
    buffer.append("/_/  \\_,_/ .__/\\__/___/\\__/_/  \\_, / /____/\n");
    f.format("        /_/                   /___/  %s%s\n\n", version, productionMode ? "" : " (development mode)");
    // log multi-line string with OS-specific line endings (TAP5-2294)
    logger.info(buffer.toString().replaceAll("\\n", System.getProperty("line.separator")));
}

98. RecordedRouteGPXFormatter#create()

Project: MozStumbler
File: RecordedRouteGPXFormatter.java
// ===========================================================
// Fields
// ===========================================================
// ===========================================================
// Constructors
// ===========================================================
// ===========================================================
// Getter & Setter
// ===========================================================
// ===========================================================
// Methods from SuperClass/Interfaces
// ===========================================================
// ===========================================================
// Methods
// ===========================================================
/**
     * Creates a String in the following XML format:
     * <p/>
     * <PRE>
     * <?xml version="1.0"?>
     * <gpx version="1.1" creator="AndNav - http://www.andnav.org - Android Navigation System" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
     * <time>2008-09-22T00:46:20Z</time>
     * <trk>
     * <name>plusminus--yyyyMMdd_HHmmss-yyyyMMdd_HHmmss</name>
     * <trkseg>
     * <trkpt lat="49.472767" lon="8.654174">
     * <time>2008-09-22T00:46:20Z</time>
     * </trkpt>
     * <trkpt lat="49.472797" lon="8.654102">
     * <time>2008-09-22T00:46:35Z</time>
     * </trkpt>
     * <trkpt lat="49.472802" lon="8.654185">
     * <time>2008-09-22T00:46:50Z</time>
     * </trkpt>
     * </trkseg>
     * </trk>
     * </gpx>
     * </PRE>
     */
public static String create(final List<RecordedGeoPoint> someRecords) throws IllegalArgumentException {
    if (someRecords == null) {
        throw new IllegalArgumentException("Records may not be null.");
    }
    if (someRecords.size() == 0) {
        throw new IllegalArgumentException("Records size == 0");
    }
    final StringBuilder sb = new StringBuilder();
    final Formatter f = new Formatter(sb);
    sb.append(XML_VERSION);
    f.format(GPX_TAG, OSM_CREATOR_INFO);
    f.format(GPX_TAG_TIME, Util.convertTimestampToUTCString(System.currentTimeMillis()));
    sb.append(GPX_TAG_TRACK);
    f.format(GPX_TAG_TRACK_NAME, OSM_USERNAME + "--" + formatterCompleteDateTime.format(new Date(someRecords.get(0).getTimeStamp()).getTime()) + "-" + formatterCompleteDateTime.format(new Date(someRecords.get(someRecords.size() - 1).getTimeStamp()).getTime()));
    sb.append(GPX_TAG_TRACK_SEGMENT);
    for (final RecordedGeoPoint rgp : someRecords) {
        f.format(GPX_TAG_TRACK_SEGMENT_POINT, rgp.getLatitudeAsDouble(), rgp.getLongitudeAsDouble());
        f.format(GPX_TAG_TRACK_SEGMENT_POINT_TIME, Util.convertTimestampToUTCString(rgp.getTimeStamp()));
        if (rgp.mNumSatellites != NOT_SET) {
            f.format(GPX_TAG_TRACK_SEGMENT_POINT_SAT, rgp.mNumSatellites);
        }
        sb.append(GPX_TAG_TRACK_SEGMENT_POINT_CLOSE);
    }
    sb.append(GPX_TAG_TRACK_SEGMENT_CLOSE).append(GPX_TAG_TRACK_CLOSE).append(GPX_TAG_CLOSE);
    return sb.toString();
}

99. LogLine#toString()

Project: log-synth
File: LogLine.java
public String toString() {
    Formatter r = new Formatter();
    r.format("{t: %.3f, cookie:\"%08x\", ip:\"%s\", query:", t, cookie, ip.getHostAddress());
    String sep = "[";
    for (String term : query) {
        r.format("%s\"%s\"", sep, term);
        sep = ",";
    }
    r.format("]}");
    return r.toString();
}

100. HistogramBaseIntStatsPerf#formatData()

Project: databus
File: HistogramBaseIntStatsPerf.java
private String formatData(String formatStr) {
    Formatter fmt = new Formatter();
    fmt.format(formatStr, _config.getCapacity(), _config.getBucketsNum(), _config.getDropNum(), 1.0 * _addTime / (2.0 * DATA_POINTS_NUM) - _procTime / 300000.0, 1.0 * _calcTime);
    fmt.flush();
    return fmt.toString();
}