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:org.apache.hadoop.util.Crc32PerformanceTest.java

static void printSystemProperties(PrintStream out) {
    final String[] names = { "java.version", "java.runtime.name", "java.runtime.version", "java.vm.version",
            "java.vm.vendor", "java.vm.name", "java.vm.specification.version", "java.specification.version",
            "os.arch", "os.name", "os.version" };
    int max = 0;/* ww w. jav a2s .c om*/
    for (String n : names) {
        if (n.length() > max) {
            max = n.length();
        }
    }

    final Properties p = System.getProperties();
    for (String n : names) {
        out.printf("%" + max + "s = %s\n", n, p.getProperty(n));
    }
}

From source file:com.bjond.Main.java

/**
*  Given an input stream _in_ to an audit log, the unobfuscated log will be stream to _out_.
* 
* @param in//from   ww  w.ja  v a2  s. c o  m
* @param out
* 
* @throws IOException
* @throws SQLException
*/
public static void process(final InputStream in, final OutputStream out) throws IOException, SQLException {
    log.info("Execution begins...");

    // Generate the POSTGRESQL URL form system envirionment variables.
    POSTGRESQL_URL = String.format("jdbc:postgresql://%s:%s/%s", OPENSHIFT_POSTGRESQL_DB_HOST,
            OPENSHIFT_POSTGRESQL_DB_PORT, OPENSHIFT_APP_NAME);

    try (final Connection db = DriverManager.getConnection(POSTGRESQL_URL, OPENSHIFT_POSTGRESQL_DB_USERNAME,
            OPENSHIFT_POSTGRESQL_DB_PASSWORD)) {

        final PrintStream outPrintStream = new PrintStream(out, true, "UTF-8");
        final Reader inReader = new InputStreamReader(in, "UTF-8");
        final Iterable<CSVRecord> records = CSVFormat.DEFAULT.withQuote('\'').parse(inReader);

        log.info("PostgreSQL DB connectiion valid: {}", db.isValid(1000));

        records.forEach(record -> {
            record.iterator().forEachRemaining(e -> {
                try {
                    if (!e.isEmpty()) {
                        final String[] tuple = keyValueSplitter(e);
                        outPrintStream.printf("%s='%s',", tuple[0], resolve(db, tuple[0], tuple[1]));
                    }
                } catch (final Exception exception) {
                    log.error("unexpected error on " + e, exception);
                }
            });

            outPrintStream.printf("%n"); // EOL
        });
    }

    log.info("Execution ends...");
}

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

public static void writeSeriesFile(AbstractProject<?, ?> project, String baseDateStr, String fileName,
        final AbstractBuild<?, ?> shimeBuild, PrintStream out, PrintStream err) {
    // stdout.printf("[%s]\n",
    // shimeBuild.getRootDir().getAbsolutePath());
    // stdout.printf("[%s]:[%s]:[%s]\n", baseDateStr,
    // shimeBuild.getNumber(), shimeBuild.getId());
    String prevData = PMUtils.findSeriesFile(project, fileName, out, err);
    String currentData = PMUtils.appendData(prevData, shimeBuild.getNumber(), baseDateStr);
    File file = new File(shimeBuild.getRootDir().getAbsolutePath(), fileName);
    WriteUtils.writeFile(currentData.getBytes(), file);
    out.printf("EVMn?t@C(%s)?Lrh #%s ???B\n", fileName,
            shimeBuild.getNumber());/*from w ww .j a v  a  2  s . c  om*/
    out.printf("???: #%s \n", shimeBuild.getRootDir().getAbsolutePath());
}

From source file:hudson.Util.java

/**
 * Creates a symlink to baseDir+targetPath at baseDir+symlinkPath.
 * <p>/*from w w  w.ja  va 2s  .c  om*/
 * If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
 *
 * @param baseDir
 *      Base directory to resolve the 'symlinkPath' parameter.
 * @param targetPath
 *      The file that the symlink should point to.
 * @param symlinkPath
 *      Where to create a symlink in.
 */
public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener)
        throws InterruptedException {
    if (Functions.isWindows() || NO_SYMLINK)
        return;

    try {
        String errmsg = "";
        // if a file or a directory exists here, delete it first.
        // try simple delete first (whether exists() or not, as it may be symlink pointing
        // to non-existent target), but fallback to "rm -rf" to delete non-empty dir.
        File symlinkFile = new File(baseDir, symlinkPath);
        if (!symlinkFile.delete() && symlinkFile.exists())
            // ignore a failure.
            new LocalProc(new String[] { "rm", "-rf", symlinkPath }, new String[0], listener.getLogger(),
                    baseDir).join();

        int r;
        if (!SYMLINK_ESCAPEHATCH) {
            try {
                r = LIBC.symlink(targetPath, symlinkFile.getAbsolutePath());
                if (r != 0) {
                    r = Native.getLastError();
                    errmsg = LIBC.strerror(r);
                }
            } catch (LinkageError e) {
                // if JNA is unavailable, fall back.
                // we still prefer to try JNA first as PosixAPI supports even smaller platforms.
                r = PosixAPI.get().symlink(targetPath, symlinkFile.getAbsolutePath());
            }
        } else // escape hatch, until we know that the above works well.
            r = new LocalProc(new String[] { "ln", "-s", targetPath, symlinkPath }, new String[0],
                    listener.getLogger(), baseDir).join();
        if (r != 0)
            listener.getLogger()
                    .println(String.format("ln -s %s %s failed: %d %s", targetPath, symlinkFile, r, errmsg));
    } catch (IOException e) {
        PrintStream log = listener.getLogger();
        log.printf("ln %s %s failed\n", targetPath, new File(baseDir, symlinkPath));
        Util.displayIOException(e, listener);
        e.printStackTrace(log);
    }
}

From source file:com.hp.application.automation.tools.run.SvExportBuilder.java

private void switchToStandBy(ServiceInfo service, IChmodeProcessor chmodeProcessor, ICommandExecutor exec,
        PrintStream logger) throws CommandExecutorException, SVCParseException, CommunicatorException {

    logger.printf("  Switching service '%s' [%s] to Stand-By mode before export%n", service.getName(),
            service.getId());// ww w.j av  a2 s  .  c  om
    ChmodeProcessorInput chmodeInput = new ChmodeProcessorInput(model.isForce(), null, service.getId(), null,
            null, ServiceRuntimeConfiguration.RuntimeMode.STAND_BY, false, false);
    chmodeProcessor.process(chmodeInput, exec);
}

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

private static void printSplitLine(PrintStream out, String name) {
    out.printf("%.78s%c%n", name, name.length() > 78 ? '>' : ' ');
    for (int at = 78; name.length() > at; at += 77)
        out.printf(">%.77s%c%n", name.substring(at), name.length() > at + 77 ? '>' : ' ');
}

From source file:hudson.Util.java

/**
 * Creates a symlink to baseDir+targetPath at baseDir+symlinkPath.
 * <p>//from  www  . ja v  a 2  s. c o m
 * If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
 *
 * @param baseDir
 *      Base directory to resolve the 'symlinkPath' parameter.
 * @param targetPath
 *      The file that the symlink should point to.
 * @param symlinkPath
 *      Where to create a symlink in.
 */
public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener)
        throws InterruptedException {
    if (Functions.isWindows() || NO_SYMLINK)
        return;

    try {
        String errmsg = "";
        // if a file or a directory exists here, delete it first.
        // try simple delete first (whether exists() or not, as it may be symlink pointing
        // to non-existent target), but fallback to "rm -rf" to delete non-empty dir.
        File symlinkFile = new File(baseDir, symlinkPath);
        if (!symlinkFile.delete() && symlinkFile.exists())
            // ignore a failure.
            new LocalProc(new String[] { "rm", "-rf", symlinkPath }, new String[0], listener.getLogger(),
                    baseDir).join();

        Integer r = null;
        if (!SYMLINK_ESCAPEHATCH) {
            try {
                r = LIBC.symlink(targetPath, symlinkFile.getAbsolutePath());
                if (r != 0) {
                    r = Native.getLastError();
                    errmsg = LIBC.strerror(r);
                }
            } catch (LinkageError e) {
                // if JNA is unavailable, fall back.
                // we still prefer to try JNA first as PosixAPI supports even smaller platforms.
                if (PosixAPI.supportsNative()) {
                    r = PosixAPI.get().symlink(targetPath, symlinkFile.getAbsolutePath());
                }
            }
        }
        if (r == null) {
            // if all else fail, fall back to the most expensive approach of forking a process
            r = new LocalProc(new String[] { "ln", "-s", targetPath, symlinkPath }, new String[0],
                    listener.getLogger(), baseDir).join();
        }
        if (r != 0)
            listener.getLogger()
                    .println(String.format("ln -s %s %s failed: %d %s", targetPath, symlinkFile, r, errmsg));
    } catch (IOException e) {
        PrintStream log = listener.getLogger();
        log.printf("ln %s %s failed%n", targetPath, new File(baseDir, symlinkPath));
        Util.displayIOException(e, listener);
        e.printStackTrace(log);
    }
}

From source file:hudson.Util.java

/**
 * Creates a symlink to baseDir+targetPath at baseDir+symlinkPath.
 * <p>/*from ww w.j  av a 2s.c  om*/
 * If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
 *
 * @param baseDir
 *      Base directory to resolve the 'symlinkPath' parameter.
 * @param targetPath
 *      The file that the symlink should point to.
 * @param symlinkPath
 *      Where to create a symlink in.
 */
public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener)
        throws InterruptedException {
    if (Functions.isWindows() || NO_SYMLINK)
        return;

    try {
        String errmsg = "";
        // if a file or a directory exists here, delete it first.
        // try simple delete first (whether exists() or not, as it may be symlink pointing
        // to non-existent target), but fallback to "rm -rf" to delete non-empty dir.
        File symlinkFile = new File(baseDir, symlinkPath);
        if (!symlinkFile.delete() && symlinkFile.exists())
            // ignore a failure.
            new LocalProc(new String[] { "rm", "-rf", symlinkPath }, new String[0], listener.getLogger(),
                    baseDir).join();

        int r;
        if (!SYMLINK_ESCAPEHATCH) {
            try {
                r = LIBC.symlink(targetPath, symlinkFile.getAbsolutePath());
                if (r != 0) {
                    r = Native.getLastError();
                    errmsg = LIBC.strerror(r);
                }
            } catch (LinkageError e) {
                // if JNA is unavailable, fall back.
                // we still prefer to try JNA first as PosixAPI supports even smaller platforms.
                r = PosixAPI.get().symlink(targetPath, symlinkFile.getAbsolutePath());
            }
        } else // escape hatch, until we know that the above works well.
            r = new LocalProc(new String[] { "ln", "-s", targetPath, symlinkPath }, new String[0],
                    listener.getLogger(), baseDir).join();
        if (r != 0)
            listener.getLogger()
                    .println(String.format("ln -s %s %s failed: %d %s", targetPath, symlinkFile, r, errmsg));
    } catch (IOException e) {
        PrintStream log = listener.getLogger();
        log.printf("ln %s %s failed%n", targetPath, new File(baseDir, symlinkPath));
        Util.displayIOException(e, listener);
        e.printStackTrace(log);
    }
}

From source file:hudson.Util.java

/**
 * Creates a symlink to baseDir+targetPath at baseDir+symlinkPath.
 * <p>//  ww  w  .j  av  a 2 s .c  om
 * If there's a prior symlink at baseDir+symlinkPath, it will be overwritten.
 *
 * @param baseDir
 *      Base directory to resolve the 'symlinkPath' parameter.
 * @param targetPath
 *      The file that the symlink should point to.
 * @param symlinkPath
 *      Where to create a symlink in.
 */
public static void createSymlink(File baseDir, String targetPath, String symlinkPath, TaskListener listener)
        throws InterruptedException {
    if (Functions.isWindows() || NO_SYMLINK) {
        return;
    }

    try {
        String errmsg = "";
        // if a file or a directory exists here, delete it first.
        // try simple delete first (whether exists() or not, as it may be symlink pointing
        // to non-existent target), but fallback to "rm -rf" to delete non-empty dir.
        File symlinkFile = new File(baseDir, symlinkPath);
        if (!symlinkFile.delete() && symlinkFile.exists()) // ignore a failure.
        {
            new LocalProc(new String[] { "rm", "-rf", symlinkPath }, new String[0], listener.getLogger(),
                    baseDir).join();
        }

        boolean success = false;

        try {
            success = NativeUtils.getInstance().createSymlink(targetPath, baseDir);
        } catch (NativeAccessException ex) {
            errmsg = "Native function mod failed" + NativeUtils.getInstance().getLastUnixError();
        }
        if (!success) { // escape hatch, until we know that the above works well.
            success = new LocalProc(new String[] { "ln", "-s", targetPath, symlinkPath }, new String[0],
                    listener.getLogger(), baseDir).join() == 0;
        }
        if (!success) {
            listener.getLogger()
                    .println(String.format("ln -s %s %s failed: %s", targetPath, symlinkFile, errmsg));
        }
    } catch (IOException e) {
        PrintStream log = listener.getLogger();
        log.printf("ln %s %s failed\n", targetPath, new File(baseDir, symlinkPath));
        Util.displayIOException(e, listener);
        e.printStackTrace(log);
    }
}

From source file:gov.llnl.ontology.mapreduce.stats.WordnetShortestPathMR.java

/**
 * {@inheritDoc}// w w  w  . j a  v  a  2  s . com
 */
public int run(String[] args) throws Exception {
    // Setup and valdiate the arguments.
    ArgOptions options = new ArgOptions();
    options.addOption('w', "wordnetDir", "The directory path to the wordnet data files", true, "PATH",
            "Required");

    options.parseOptions(args);
    if (!options.hasOption('w')) {
        System.err.println("usage: java WordnetShortestPathMR [OPTIONS] <outdir>\n" + options.prettyPrint());
    }

    // Open the wordnet reader and gather the set of all Synsets known by
    // the ontology.
    OntologyReader reader = WordNetCorpusReader.initialize(options.getStringOption('w'));
    Set<Synset> synsetSet = new HashSet<Synset>();
    for (String lemma : reader.wordnetTerms())
        for (Synset synset : reader.getSynsets(lemma))
            synsetSet.add(synset);

    // Compute each pairing of Synsets and write that pairing to a file in
    // HDFS.
    Synset[] synsets = synsetSet.toArray(new Synset[0]);
    PrintStream outStream = createPrintStream();
    for (int i = 0; i < synsets.length; ++i)
        for (int j = i + 1; j < synsets.length; ++j)
            outStream.printf("%s|%s\n", synsets[i].getName(), synsets[j].getName());
    outStream.close();

    // Store the wordnet directory information so that the mappers can load
    // it up.  They need it to figure out the shortest path information.
    Configuration conf = getConf();
    conf.set(WORDNET, options.getStringOption('w'));

    // Setup the job information.
    Job job = new Job(conf, "Compute Wordnet Shortest Paths");
    job.setJarByClass(WordnetShortestPathMR.class);

    job.setMapperClass(WordnetShortestPathMapper.class);

    // The input file will be the temporary file created with the synset
    // pairings.
    job.setInputFormatClass(LineDocInputFormat.class);
    FileInputFormat.addInputPath(job, new Path(TEMP_TERM_PAIR_PATH));

    // The mappers do all of the real work, so we just write their output
    // straight to disk.
    job.setCombinerClass(Reducer.class);
    job.setReducerClass(Reducer.class);
    job.setOutputFormatClass(TextOutputFormat.class);
    TextOutputFormat.setOutputPath(job, new Path(options.getPositionalArg(0)));

    // Start the job.
    job.waitForCompletion(true);

    return 0;
}