Example usage for java.io PrintStream printf

List of usage examples for java.io PrintStream printf

Introduction

In this page you can find the example usage for java.io PrintStream printf.

Prototype

public PrintStream printf(Locale l, String format, Object... args) 

Source Link

Document

A convenience method to write a formatted string to this output stream using the specified format string and arguments.

Usage

From source file:Main.java

public static void main(String[] args) {
    String s = "from java2s.com";

    PrintStream ps = new PrintStream(System.out);

    // printf this string
    ps.printf(Locale.CANADA, "This is a %s application", s);

    // flush the stream
    ps.flush();//from  www .j  a v  a 2  s .  c o  m

}

From source file:org.caffinitas.ohc.benchmark.BenchmarkOHC.java

public static void main(String[] args) throws Exception {
    Locale.setDefault(Locale.ENGLISH);
    Locale.setDefault(Locale.Category.FORMAT, Locale.ENGLISH);

    try {//from  ww w.  ja v a 2 s .co m
        CommandLine cmd = parseArguments(args);

        String[] warmUp = cmd.getOptionValue(WARM_UP, "15,5").split(",");
        int warmUpSecs = Integer.parseInt(warmUp[0]);
        int coldSleepSecs = Integer.parseInt(warmUp[1]);

        int duration = Integer.parseInt(cmd.getOptionValue(DURATION, "60"));
        int cores = Runtime.getRuntime().availableProcessors();
        if (cores >= 8)
            cores -= 2;
        else if (cores > 2)
            cores--;
        int threads = Integer.parseInt(cmd.getOptionValue(THREADS, Integer.toString(cores)));
        long capacity = Long.parseLong(cmd.getOptionValue(CAPACITY, "" + (1024 * 1024 * 1024)));
        int hashTableSize = Integer.parseInt(cmd.getOptionValue(HASH_TABLE_SIZE, "0"));
        int segmentCount = Integer.parseInt(cmd.getOptionValue(SEGMENT_COUNT, "0"));
        float loadFactor = Float.parseFloat(cmd.getOptionValue(LOAD_FACTOR, "0"));
        int keyLen = Integer.parseInt(cmd.getOptionValue(KEY_LEN, "0"));
        int chunkSize = Integer.parseInt(cmd.getOptionValue(CHUNK_SIZE, "-1"));
        int fixedKeySize = Integer.parseInt(cmd.getOptionValue(FIXED_KEY_SIZE, "-1"));
        int fixedValueSize = Integer.parseInt(cmd.getOptionValue(FIXED_VALUE_SIZE, "-1"));
        int maxEntrySize = Integer.parseInt(cmd.getOptionValue(MAX_ENTRY_SIZE, "-1"));
        boolean unlocked = Boolean.parseBoolean(cmd.getOptionValue(UNLOCKED, "false"));
        HashAlgorithm hashMode = HashAlgorithm.valueOf(cmd.getOptionValue(HASH_MODE, "MURMUR3"));

        boolean bucketHistogram = Boolean.parseBoolean(cmd.getOptionValue(BUCKET_HISTOGRAM, "false"));

        double readWriteRatio = Double.parseDouble(cmd.getOptionValue(READ_WRITE_RATIO, ".5"));

        Driver[] drivers = new Driver[threads];
        Random rnd = new Random();
        String readKeyDistStr = cmd.getOptionValue(READ_KEY_DIST, DEFAULT_KEY_DIST);
        String writeKeyDistStr = cmd.getOptionValue(WRITE_KEY_DIST, DEFAULT_KEY_DIST);
        String valueSizeDistStr = cmd.getOptionValue(VALUE_SIZE_DIST, DEFAULT_VALUE_SIZE_DIST);
        DistributionFactory readKeyDist = OptionDistribution.get(readKeyDistStr);
        DistributionFactory writeKeyDist = OptionDistribution.get(writeKeyDistStr);
        DistributionFactory valueSizeDist = OptionDistribution.get(valueSizeDistStr);
        for (int i = 0; i < threads; i++) {
            drivers[i] = new Driver(readKeyDist.get(), writeKeyDist.get(), valueSizeDist.get(), readWriteRatio,
                    rnd.nextLong());
        }

        printMessage("Initializing OHC cache...");
        OHCacheBuilder<Long, byte[]> builder = OHCacheBuilder.<Long, byte[]>newBuilder()
                .keySerializer(
                        keyLen <= 0 ? BenchmarkUtils.longSerializer : new BenchmarkUtils.KeySerializer(keyLen))
                .valueSerializer(BenchmarkUtils.serializer).capacity(capacity);
        if (cmd.hasOption(LOAD_FACTOR))
            builder.loadFactor(loadFactor);
        if (cmd.hasOption(SEGMENT_COUNT))
            builder.segmentCount(segmentCount);
        if (cmd.hasOption(HASH_TABLE_SIZE))
            builder.hashTableSize(hashTableSize);
        if (cmd.hasOption(CHUNK_SIZE))
            builder.chunkSize(chunkSize);
        if (cmd.hasOption(MAX_ENTRY_SIZE))
            builder.maxEntrySize(maxEntrySize);
        if (cmd.hasOption(UNLOCKED))
            builder.unlocked(unlocked);
        if (cmd.hasOption(HASH_MODE))
            builder.hashMode(hashMode);
        if (cmd.hasOption(FIXED_KEY_SIZE))
            builder.fixedEntrySize(fixedKeySize, fixedValueSize);

        Shared.cache = builder.build();

        printMessage("Cache configuration: instance       : %s%n" + "                     hash-table-size: %d%n"
                + "                     load-factor    : %.3f%n" + "                     segments       : %d%n"
                + "                     capacity       : %d%n", Shared.cache, Shared.cache.hashTableSizes()[0],
                Shared.cache.loadFactor(), Shared.cache.segments(), Shared.cache.capacity());

        String csvFileName = cmd.getOptionValue(CSV, null);
        PrintStream csv = null;
        if (csvFileName != null) {
            File csvFile = new File(csvFileName);
            csv = new PrintStream(new FileOutputStream(csvFile));
            csv.println("# OHC benchmark - http://github.com/snazy/ohc");
            csv.println("# ");
            csv.printf("# started on %s (%s)%n", InetAddress.getLocalHost().getHostName(),
                    InetAddress.getLocalHost().getHostAddress());
            csv.println("# ");
            csv.printf("# Warum-up/sleep seconds:   %d / %d%n", warmUpSecs, coldSleepSecs);
            csv.printf("# Duration:                 %d seconds%n", duration);
            csv.printf("# Threads:                  %d%n", threads);
            csv.printf("# Capacity:                 %d bytes%n", capacity);
            csv.printf("# Read/Write Ratio:         %f%n", readWriteRatio);
            csv.printf("# Segment Count:            %d%n", segmentCount);
            csv.printf("# Hash table size:          %d%n", hashTableSize);
            csv.printf("# Load Factor:              %f%n", loadFactor);
            csv.printf("# Additional key len:       %d%n", keyLen);
            csv.printf("# Read key distribution:    '%s'%n", readKeyDistStr);
            csv.printf("# Write key distribution:   '%s'%n", writeKeyDistStr);
            csv.printf("# Value size distribution:  '%s'%n", valueSizeDistStr);
            csv.printf("# Type: %s%n", Shared.cache.getClass().getName());
            csv.println("# ");
            csv.printf("# started at %s%n", new Date());
            Properties props = System.getProperties();
            csv.printf("# java.version:             %s%n", props.get("java.version"));
            for (Map.Entry<Object, Object> e : props.entrySet()) {
                String k = (String) e.getKey();
                if (k.startsWith("org.caffinitas.ohc."))
                    csv.printf("# %s: %s%n", k, e.getValue());
            }
            csv.printf("# number of cores: %d%n", Runtime.getRuntime().availableProcessors());
            csv.println("# ");
            csv.println("\"runtime\";" + "\"r_count\";"
                    + "\"r_oneMinuteRate\";\"r_fiveMinuteRate\";\"r_fifteenMinuteRate\";\"r_meanRate\";"
                    + "\"r_snapMin\";\"r_snapMax\";\"r_snapMean\";\"r_snapStdDev\";"
                    + "\"r_snap75\";\"r_snap95\";\"r_snap98\";\"r_snap99\";\"r_snap999\";\"r_snapMedian\";"
                    + "\"w_count\";"
                    + "\"w_oneMinuteRate\";\"w_fiveMinuteRate\";\"w_fifteenMinuteRate\";\"w_meanRate\";"
                    + "\"w_snapMin\";\"w_snapMax\";\"w_snapMean\";\"w_snapStdDev\";"
                    + "\"w_snap75\";\"w_snap95\";\"w_snap98\";\"w_snap99\";\"w_snap999\";\"w_snapMedian\"");
        }

        printMessage(
                "Starting benchmark with%n" + "   threads     : %d%n" + "   warm-up-secs: %d%n"
                        + "   idle-secs   : %d%n" + "   runtime-secs: %d%n",
                threads, warmUpSecs, coldSleepSecs, duration);

        ThreadPoolExecutor main = new ThreadPoolExecutor(threads, threads, coldSleepSecs + 1, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
                    volatile int threadNo;

                    public Thread newThread(Runnable r) {
                        return new Thread(r, "driver-main-" + threadNo++);
                    }
                });
        main.prestartAllCoreThreads();

        // warm up

        if (warmUpSecs > 0) {
            printMessage("Start warm-up...");
            runFor(warmUpSecs, main, drivers, bucketHistogram, csv);
            printMessage("");
            logMemoryUse();

            if (csv != null)
                csv.println("# warm up complete");
        }
        // cold sleep

        if (coldSleepSecs > 0) {
            printMessage("Warm up complete, sleep for %d seconds...", coldSleepSecs);
            Thread.sleep(coldSleepSecs * 1000L);
        }

        // benchmark

        printMessage("Start benchmark...");
        runFor(duration, main, drivers, bucketHistogram, csv);
        printMessage("");
        logMemoryUse();

        if (csv != null)
            csv.println("# benchmark complete");

        // finish

        if (csv != null)
            csv.close();

        System.exit(0);
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

From source file:name.livitski.databag.cli.Syntax.java

/**
 * Diagnostic entry point for the build process to check that all
 * usage strings that describe the application's syntax are present
 * in <code>usage.resources</code>.
 * Absent resources cause a <code>System.err</code> message
 * and a non-zero exit code.// w w w .ja  v a2s  . c om
 * @param args this method ignores its argument
 */
@SuppressWarnings("unchecked")
public static void main(String[] args) {
    PrintStream out = System.err;
    Resources resources = new Resources();
    final Class<Syntax> clazz = Syntax.class;
    String id = null;
    String legend = null;
    for (Option option : (Collection<Option>) OPTIONS.getOptions()) {
        try {
            id = getOptionId(option);
            legend = resources.getString(USAGE_BUNDLE, clazz, id).trim();
            if (legend.indexOf('.') < legend.length() - 1) {
                out.printf(
                        "Description of option %s must be a single sentence ending with a period. Got:%n\"%s\"%n",
                        id, legend);
                System.exit(5);
            }
            if (option.hasArg())
                resources.getString(USAGE_BUNDLE, clazz, "arg" + id);
            legend = null;
        } catch (MissingResourceException missing) {
            if (null == legend) {
                out.printf("Option \"%s\" does not have a description string in the resource bundle \"%s\"%n",
                        id, USAGE_BUNDLE);
                missing.printStackTrace(out);
                System.exit(1);
            }
            out.printf("Required argument spec \"%s\" is missing from the resource bundle \"%s\"%n",
                    getArgumentId(option), USAGE_BUNDLE);
            missing.printStackTrace(out);
            System.exit(2);
        } catch (Exception problem) {
            out.printf("Error while verifying option \"%s\" in the resource bundle \"%s\"%n", id, USAGE_BUNDLE);
            problem.printStackTrace(out);
            System.exit(-1);
        }
    }
}

From source file:com.genentech.struchk.oeStruchk.OEStruchk.java

/**
 * Command line interface to {@link OEStruchk}.
 *//*  www  .  j  ava 2 s  . c o m*/
public static void main(String[] args) throws ParseException, JDOMException, IOException {
    long start = System.currentTimeMillis();
    int nMessages = 0;
    int nErrors = 0;
    int nStruct = 0;
    System.err.printf("OEChem Version: %s\n", oechem.OEChemGetVersion());

    // create command line Options object
    Options options = new Options();
    Option opt = new Option("f", true, "specify the configuration file name");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option("noMsg", false, "Do not add any additional sd-tags to the sdf file");
    options.addOption(opt);

    opt = new Option("printRules", true, "Print HTML listing all the rules to filename.");
    options.addOption(opt);

    opt = new Option("errorsAsWarnings", false, "Treat errors as warnings.");
    options.addOption(opt);

    opt = new Option("stopForDebug", false, "Stop and read from stdin for user tu start debugger.");
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    args = cmd.getArgs();

    if (cmd.hasOption("stopForDebug")) {
        BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in));
        System.err.print("Please press return:");

        localRdr.readLine();
    }

    URL confFile;
    if (cmd.hasOption("f")) {
        confFile = new File(cmd.getOptionValue("f")).toURI().toURL();
    } else {
        confFile = getResourceURL(OEStruchk.class, "Struchk.xml");
    }
    boolean errorsAsWarnings = cmd.hasOption("errorsAsWarnings");

    if (cmd.hasOption("printRules")) {
        String fName = cmd.getOptionValue("printRules");
        PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream(fName)));
        OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings);
        structFlagAssigner.printRules(out);
        out.close();
        return;
    }

    if (args.length < 1) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("oeStruck", options);
        throw new Error("missing input file\n");
    }

    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader(args[0]));
        StringBuilder mol = new StringBuilder();
        StringBuilder data = new StringBuilder();
        PrintStream out = System.out;
        if (args.length > 1)
            out = new PrintStream(args[1]);

        // create OEStruchk from config file
        OEStruchk structFlagAssigner = new OEStruchk(confFile, CHECKConfig.ASSIGNStructFlag, errorsAsWarnings);

        OEStruchk structFlagChecker = new OEStruchk(confFile, CHECKConfig.CHECKStructFlag, errorsAsWarnings);

        Pattern sFlagPat = Pattern.compile("<StructFlag>\\s*([^\\n\\r]+)");
        String line;
        boolean inMolFile = true;
        boolean atEnd = false;
        while (!atEnd) {
            if ((line = in.readLine()) == null) {
                if ("".equals(mol.toString().trim()))
                    break;

                if (!inMolFile)
                    throw new Error("Invalid end of sd file!");

                line = "$$$$";
                atEnd = true;
            }

            if (line.startsWith("$$$$")) {

                OEStruchk oeStruchk;
                StructureFlag sFlag = null;
                Matcher mat = sFlagPat.matcher(data);
                if (!mat.find()) {
                    oeStruchk = structFlagAssigner;
                } else {
                    oeStruchk = structFlagChecker;
                    sFlag = StructureFlag.fromString(mat.group(1));
                }
                if (!oeStruchk.applyRules(mol.toString(), null, sFlag))
                    nErrors++;

                out.print(oeStruchk.getTransformedMolfile(null));

                out.print(data);

                if (!cmd.hasOption("noMsg")) {
                    List<Message> msgs = oeStruchk.getStructureMessages(null);
                    if (msgs.size() > 0) {
                        nMessages += msgs.size();

                        out.println("> <errors_oe2>");
                        for (Message msg : msgs)
                            out.printf("%s: %s\n", msg.getLevel(), msg.getText());
                        out.println();
                    }
                    //System.err.println(oeStruchk.getTransformedMolfile("substance"));
                    out.printf("> <outStereo>\n%s\n\n", oeStruchk.getStructureFlag().getName());
                    out.printf("> <TISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles(null));
                    out.printf("> <TSMI>\n%s\n\n", oeStruchk.getTransformedSmiles(null));
                    out.printf("> <pISM>\n%s\n\n", oeStruchk.getTransformedIsoSmiles("parent"));
                    out.printf("> <salt>\n%s\n\n", oeStruchk.getSaltCode());
                    out.printf("> <stereoCounts>\n%s.%s\n\n", oeStruchk.countChiralCentersStr(),
                            oeStruchk.countStereoDBondStr());
                }

                out.println(line);
                nStruct++;

                mol.setLength(0);
                data.setLength(0);

                inMolFile = true;
            } else if (!inMolFile || line.startsWith(">")) {
                inMolFile = false;
                data.append(line).append("\n");
            } else {
                mol.append(line).append("\n");
            }
        }

        structFlagAssigner.delete();
        structFlagChecker.delete();

    } catch (Exception e) {
        throw new Error(e);
    } finally {
        System.err.printf("Checked %d structures %d errors, %d messages in %dsec\n", nStruct, nErrors,
                nMessages, (System.currentTimeMillis() - start) / 1000);
        if (in != null)
            in.close();
    }
    if (cmd.hasOption("stopForDebug")) {
        BufferedReader localRdr = new BufferedReader(new InputStreamReader(System.in));
        System.err.print("Please press return:");

        localRdr.readLine();
    }
}

From source file:de.tynne.benchmarksuite.Main.java

private static void listBenchmarks(BenchmarkProducer benchmarkProducer, PrintStream ps) {
    benchmarkProducer.get().stream().forEach((b) -> ps.printf("%s: %s\n", b.getId(), b.getName()));
    ps.flush();//ww w .j  a  va  2 s .co  m
}

From source file:de.tynne.benchmarksuite.Main.java

private static void listSuites(Map<BenchmarkSuite, BenchmarkProducer> suites, PrintStream ps) {
    suites.entrySet().stream().sorted(//from w w w.  j  a v  a  2  s .  c  o  m
            (a, b) -> nameFor(a.getKey(), a.getValue()).compareToIgnoreCase(nameFor(b.getKey(), b.getValue())))
            .forEach((e) -> {
                ps.printf("%s: %s\n", nameFor(e.getKey(), e.getValue()), e.getKey().enabled());
            });
    ps.flush();
}

From source file:Main.java

/***
 *  Print every attribute and value of a node, one line at a time.
 *  If {@link entry} is null, then outputs "&lt;null/&gt;".
 *
 * @param outs where to send output, cannot be null.
 * @param entry XML node to examine, OK if null.
 *///w  ww  . j  a v a2  s  . co  m
public static void XmlPrintAttrs(PrintStream outs, Node entry) {
    if (entry == null) {
        outs.print("<null/>");
        return;
    }

    //  see http://www.w3.org/2003/01/dom2-javadoc/org/w3c/dom/NamedNodeMap.html
    NamedNodeMap attrs = entry.getAttributes();

    for (int k = attrs.getLength(); --k >= 0;) {
        Node n = attrs.item(k);
        outs.printf("+++ has attr %s = %s\n", n.getNodeName(), n.getNodeValue());
    }
}

From source file:org.openmainframe.ade.core.statistics.TimingStatistics.java

/** Print the statistics report to specified stream for a specified measure */
static public void printSummary(PrintStream out, String measure) {
    if (measure == null) {
        out.println("Profiling statistics: (hh:mm:ss)");
    }/*  www.j a va  2s.  co  m*/
    for (Measure m : getSortedMeasures()) {
        if (measure == null || m.mName.equals(measure)) {
            out.printf("  %-25s: %s", m.mName, getMeasures().get(m.mName).toString());
            out.println();
        }
    }
}

From source file:it.units.malelab.ege.util.Utils.java

public static <T> void prettyPrintTree(Node<T> node, PrintStream ps) {
    ps.printf("%" + (1 + node.getAncestors().size() * 2) + "s-%s%n", "", node.getContent());
    for (Node<T> child : node.getChildren()) {
        prettyPrintTree(child, ps);// w  ww. j a va 2  s  . c o m
    }
}

From source file:nu.mine.kino.jenkins.plugins.projectmanagement.utils.PMUtils.java

public static void writeBaseDateFile(String baseDateStr, final AbstractBuild<?, ?> shimeBuild,
        PrintStream out) {
    WriteUtils.writeFile(baseDateStr.getBytes(),
            new File(shimeBuild.getRootDir().getAbsolutePath(), PMConstants.DATE_DAT_FILENAME));
    out.printf("?t@C(%s)rh #%s ???B\n", PMConstants.DATE_DAT_FILENAME,
            shimeBuild.getNumber());//from   ww  w  . j a  va  2  s .  c  om
    out.printf("???: %s \n", shimeBuild.getRootDir().getAbsolutePath());
}