Example usage for java.lang ProcessBuilder redirectOutput

List of usage examples for java.lang ProcessBuilder redirectOutput

Introduction

In this page you can find the example usage for java.lang ProcessBuilder redirectOutput.

Prototype

public ProcessBuilder redirectOutput(File file) 

Source Link

Document

Sets this process builder's standard output destination to a file.

Usage

From source file:com.kdmanalytics.toif.framework.toolAdaptor.ToolAdaptor.java

/**
 * Run the tool. A command needs to be constructed, the same as you would if
 * you were running it from the command line.
 * //from w  w  w .j  a  v a2 s.co m
 * @return return the process which was created by running the tool.
 * @throws ToifException
 */
public java.io.File runTool() throws ToifException {
    ProcessBuilder process = null;
    java.io.File file = null;

    final String[] command = getCommands();

    synchronized (this) {
        StringBuilder sb = new StringBuilder();
        for (String cmd : command) {
            sb.append(cmd).append(" ");
        }
    }

    process = new ProcessBuilder(command);

    // DISABLED Nicing Windows. It seems that the cmd is dodgy and
    // occasionally loses the path that we set in the environment,
    // and it certainly does not like having absolute paths to
    // executables (at least ones with spaces).
    // Put the executable directory in path
    // if(SystemUtils.IS_OS_WINDOWS && execDir != null)
    // {
    // Map<String,String> env = process.environment();
    // String envPath = env.get("PATH");
    // if(envPath != null)
    // {
    // envPath = execDir.toString() + ";" + envPath;
    // }
    // else
    // {
    // envPath = execDir.toString();
    // }
    // System.err.println("SETTING PATH: " + envPath);
    // env.put("PATH", envPath);
    // }

    // This doesn't work without spawning a bat or shell wrapper
    // // Extra path information
    // java.io.File paths = options.getPaths();
    // if(paths != null)
    // {
    // Map<String,String> env = process.environment();
    // String envPath = env.get("PATH");
    // if(envPath != null)
    // {
    // envPath = paths + ";" + envPath;
    // }
    // else
    // {
    // envPath = paths.toString();
    // }
    // System.err.println("SETTING PATH: " + envPath);
    // env.put("PATH", envPath);
    // }

    if (workingDirectory != null) {
        process.directory(workingDirectory);
    }

    java.io.File outputDirectory = options.getOutputDirectory();
    outputDirectory.mkdirs();

    file = null;
    if (adaptorImpl.getAdaptorName().equals("Splint")) {
        file = new java.io.File(outputDirectory,
                options.getInputFile().getName() + "." + adaptorImpl.getRuntoolName());

        java.io.File file2 = new java.io.File(outputDirectory,
                options.getInputFile().getName() + "-err." + adaptorImpl.getRuntoolName());

        java.io.File tmp = null;
        try {
            tmp = java.io.File.createTempFile("splint", ".tmp");
        } catch (IOException e) {
            LOG.error("", e);
            throw new ToifException();
        }
        if (tmp != null) {
            tmp.deleteOnExit();
            process.redirectOutput(tmp);
        }
        process.redirectError(file2);
    }
    // if (adaptorImpl.getAdaptorName().equals("Cppcheck"))
    // {
    // file = new java.io.File(options.getOutputDirectory(),
    // options.getInputFile().getName() + "." +
    // adaptorImpl.getRuntoolName());
    // java.io.File file2 = new java.io.File(options.getOutputDirectory(),
    // options.getInputFile().getName() + "-err."
    // + adaptorImpl.getRuntoolName());
    //
    // process.redirectOutput(file2);
    // process.redirectError(file);
    // }
    else {
        file = new java.io.File(outputDirectory,
                options.getInputFile().getName() + "." + adaptorImpl.getRuntoolName());
        java.io.File file2 = new java.io.File(outputDirectory,
                options.getInputFile().getName() + "-err." + adaptorImpl.getRuntoolName());

        process.redirectOutput(file);
        process.redirectError(file2);
    }
    try {
        Process p = process.start();

        p.waitFor();

        // Check the exit value to ensure that process did not fail
        // except splint, splint is stupid and is always non-zero
        String name = adaptorImpl.getAdaptorName();
        if ((p.exitValue() != 0) && (!"Splint".equals(name))) {
            int status = p.exitValue();
            final String msg = "Adaptor process failure detected for '" + name + "': status=" + status + " "
                    + options.getAdaptor().toString();

            LOG.error(msg);
            throw new ToifException(msg);
        }
        return file;
    } catch (final IOException | InterruptedException e) {
        final String msg = options.getAdaptor().toString() + ": Could not write to output. " + e;
        LOG.error(msg);
        throw new ToifException(e);
    }
}

From source file:de.huberlin.wbi.cuneiform.core.cre.LocalThread.java

@Override
public void run() {

    Path scriptFile, location, successMarker, reportFile, callLocation, stdErrFile, stdOutFile;
    // Path lockMarker;
    Process process;/*from w  w  w  .j  ava 2s.c  om*/
    int exitValue;
    Set<JsonReportEntry> report;
    JsonReportEntry entry;
    String line;
    StringBuffer buf;
    Path srcPath, destPath;
    ProcessBuilder processBuilder;
    Ticket ticket;
    String script, stdOut, stdErr;
    long tic, toc;
    JSONObject obj;
    Message msg;
    Charset cs;
    int trial;
    boolean suc;
    Exception ex;

    if (log.isDebugEnabled())
        log.debug("Starting up local thread for ticket " + invoc.getTicketId() + ".");

    if (invoc == null)
        throw new NullPointerException("Invocation must not be null.");

    ticket = invoc.getTicket();
    process = null;
    stdOut = null;
    stdErr = null;
    // lockMarker = null;
    script = null;
    successMarker = null;
    cs = Charset.forName("UTF-8");

    try {

        callLocation = Paths.get(System.getProperty("user.dir"));
        location = buildDir.resolve(String.valueOf(invoc.getTicketId()));
        // lockMarker = location.resolve( Invocation.LOCK_FILENAME );
        successMarker = location.resolve(Invocation.SUCCESS_FILENAME);
        reportFile = location.resolve(Invocation.REPORT_FILENAME);
        script = invoc.toScript();

        // if( Files.exists( lockMarker ) )
        //   throw new IOException( "Lock held on ticket "+invoc.getTicketId() );

        if (!Files.exists(successMarker)) {

            deleteIfExists(location);
            Files.createDirectories(location);

            // Files.createFile( lockMarker );

            scriptFile = invoc.getExecutablePath(location);

            Files.createFile(scriptFile,
                    PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---")));

            // write executable script
            try (BufferedWriter writer = Files.newBufferedWriter(scriptFile, cs, StandardOpenOption.CREATE)) {
                writer.write(script);
            }

            // write executable log entry
            try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.CREATE)) {
                writer.write(ticket.getExecutableLogEntry().toString());
                writer.write('\n');
            }

            for (String filename : invoc.getStageInList()) {

                if (filename.charAt(0) == '/')
                    throw new UnsupportedOperationException("Absolute path encountered '" + filename + "'.");

                srcPath = centralRepo.resolve(filename);
                destPath = location.resolve(filename);

                if (!Files.exists(srcPath)) {

                    srcPath = callLocation.resolve(filename);
                    if (log.isTraceEnabled())
                        log.trace("Resolving relative path '" + srcPath + "'.");
                } else

                if (log.isTraceEnabled())
                    log.trace("Resolving path to central repository '" + srcPath + "'.");

                if (log.isTraceEnabled())
                    log.trace("Trying to create symbolic link from '" + srcPath + "' to '" + destPath + "'.");

                if (!Files.exists(destPath.getParent()))
                    Files.createDirectories(destPath.getParent());

                Files.createSymbolicLink(destPath, srcPath);

            }

            // run script
            processBuilder = new ProcessBuilder(invoc.getCmd());
            processBuilder.directory(location.toFile());

            stdOutFile = location.resolve(Invocation.STDOUT_FILENAME);
            stdErrFile = location.resolve(Invocation.STDERR_FILENAME);

            processBuilder.redirectOutput(stdOutFile.toFile());
            processBuilder.redirectError(stdErrFile.toFile());

            trial = 1;
            suc = false;
            ex = null;
            tic = System.currentTimeMillis();
            do {
                try {
                    process = processBuilder.start();

                    suc = true;
                } catch (IOException e) {

                    ex = e;
                    if (log.isWarnEnabled())
                        log.warn("Unable to start process on trial " + (trial++) + " Waiting " + WAIT_INTERVAL
                                + "ms: " + e.getMessage());
                    Thread.sleep(WAIT_INTERVAL);
                }
            } while (suc == false && trial <= MAX_TRIALS);

            if (process == null) {

                ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, ex, script, null, null));
                // Files.delete( lockMarker );
                return;
            }

            exitValue = process.waitFor();
            toc = System.currentTimeMillis();

            try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.APPEND)) {

                obj = new JSONObject();
                obj.put(JsonReportEntry.LABEL_REALTIME, toc - tic);
                entry = invoc.createJsonReportEntry(tic, JsonReportEntry.KEY_INVOC_TIME, obj);

                writer.write(entry.toString());
                writer.write('\n');

                try (BufferedReader reader = Files.newBufferedReader(stdOutFile, cs)) {

                    buf = new StringBuffer();
                    while ((line = reader.readLine()) != null)
                        buf.append(line).append('\n');

                    stdOut = buf.toString();

                    if (!stdOut.isEmpty()) {
                        entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDOUT, stdOut);
                        writer.write(entry.toString());
                        writer.write('\n');
                    }
                }

                try (BufferedReader reader = Files.newBufferedReader(stdErrFile, cs)) {

                    buf = new StringBuffer();
                    while ((line = reader.readLine()) != null)
                        buf.append(line).append('\n');

                    stdErr = buf.toString();
                    if (!stdErr.isEmpty()) {

                        entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDERR, stdErr);
                        writer.write(entry.toString());
                        writer.write('\n');
                    }
                }

                if (exitValue == 0)

                    Files.createFile(successMarker);

                else {

                    ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, null, script, stdOut, stdErr));
                    // Files.delete( lockMarker );
                    return;

                }
            }

        }

        // gather report
        report = new HashSet<>();
        try (BufferedReader reader = Files.newBufferedReader(reportFile, cs)) {

            while ((line = reader.readLine()) != null) {

                line = line.trim();

                if (line.isEmpty())
                    continue;

                entry = new JsonReportEntry(line);

                // If the report comes from the hard cache then the run id
                // is different from the run id of this invocation. This is
                // corrected here.
                entry.setRunId(invoc.getRunId());

                report.add(entry);
            }

        }

        invoc.evalReport(report);

        // create link in central data repository
        for (String f : invoc.getStageOutList()) {

            srcPath = location.resolve(f);
            destPath = centralRepo.resolve(f);

            if (Files.exists(destPath))
                continue;

            if (log.isTraceEnabled())
                log.trace("Creating link from " + srcPath + " to " + destPath + ".");

            Files.createSymbolicLink(destPath, srcPath);
        }

        ticketSrc.sendMsg(new TicketFinishedMsg(cre, invoc.getTicket(), report));

        if (log.isTraceEnabled())
            log.trace("Local thread ran through without exception.");

        // Files.deleteIfExists( lockMarker );

    } catch (InterruptedException e) {

        if (log.isTraceEnabled())
            log.trace("Local thread has been interrupted.");
    } catch (Exception e) {

        if (log.isTraceEnabled())
            log.trace("Something went wrong. Deleting success marker if present.");

        if (successMarker != null)
            try {
                Files.deleteIfExists(successMarker);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        msg = new TicketFailedMsg(cre, ticket, e, script, stdOut, stdErr);

        ticketSrc.sendMsg(msg);

    } finally {

        if (process != null) {

            if (log.isDebugEnabled())
                log.debug("Stopping local thread for ticket " + invoc.getTicketId() + ".");

            process.destroy();
        }
    }
}