Example usage for java.lang ProcessBuilder directory

List of usage examples for java.lang ProcessBuilder directory

Introduction

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

Prototype

File directory

To view the source code for java.lang ProcessBuilder directory.

Click Source Link

Usage

From source file:net.sf.jasperreports.customvisualization.export.CVElementPhantomJSImageDataProvider.java

/**
 * Executes a command within the given timeout.
 * /*  w  w w.jav a  2 s.  co  m*/
 * @param args
 * @param currentDirectory
 * @param timeout
 */
private static void runCommand(String[] args, File currentDirectory, final int timeout) {
    Thread loggingThread = null;
    Thread interruptingThread = null;

    try {
        String cmd = "";
        for (String arg : args) {
            cmd += " " + arg;
        }

        if (log.isDebugEnabled()) {
            log.debug("Executing external command: " + cmd);
        }
        //System.out.println(cmd);

        ProcessBuilder pb = new ProcessBuilder(Arrays.asList(args));
        pb.directory(currentDirectory);

        final Process externalProcess = pb.start();
        final StringBuilder processOutput = new StringBuilder();

        final boolean[] success = new boolean[1];
        success[0] = false;

        loggingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                BufferedReader br = null;
                try {
                    br = new BufferedReader(new InputStreamReader(externalProcess.getInputStream()));
                    String line;
                    while ((line = br.readLine()) != null) {
                        processOutput.append(line).append("\n");

                        if (line.indexOf("SCRIPT_SUCCESS") >= 0) {
                            success[0] = true;
                            killProcess(externalProcess, 100);
                        } else if (line.indexOf("SCRIPT_ERROR") >= 0) {
                            success[0] = false;
                            killProcess(externalProcess, 100);
                        }
                    }

                    if (log.isDebugEnabled()) {
                        log.debug("External process output:\n" + processOutput.toString());
                    }
                } catch (IOException e) {
                    if (log.isDebugEnabled()) {
                        log.debug(e.getMessage());
                    }
                } finally {
                    if (br != null) {
                        try {
                            br.close();
                        } catch (IOException e) {
                            if (log.isWarnEnabled()) {
                                log.warn("Failed to close phantomjs process' inputstream", e);
                            }
                        }
                    }
                }
            }
        });

        interruptingThread = new Thread(new Runnable() {
            @Override
            public void run() {
                if (killProcess(externalProcess, timeout)) {
                    success[0] = false;
                }
            }

        });
        loggingThread.start();
        interruptingThread.start();
        externalProcess.waitFor();

        // We should not care if the phantomjs process does not end on time if it succeeds in producing the desired output.
        if (externalProcess.exitValue() != 0 && !success[0]) {
            // FIXME we should do loggingThread.join(millis) because the
            // process might end before its output if fully processed

            throw new JRRuntimeException("External process did not end properly; exit value: "
                    + externalProcess.exitValue()
                    + (processOutput.length() > 0 ? "; process output:\n" + processOutput + "\n" : "."));
        }

    } catch (IOException e) {
        throw new JRRuntimeException(e);
    } catch (InterruptedException e) {
        throw new JRRuntimeException(e);
    } finally {

        if (interruptingThread != null && interruptingThread.isAlive()) {
            try {
                interruptingThread.interrupt();
            } catch (Exception ex) {
            }
        }
        if (loggingThread != null && loggingThread.isAlive()) {
            try {
                loggingThread.interrupt();
            } catch (Exception ex) {
            }
        }
    }
}

From source file:org.jsweet.transpiler.util.ProcessUtil.java

/**
 * Runs the given command.//from w  w  w.  j av  a 2s . c  o m
 * 
 * @param command
 *            the command name
 * @param directory
 *            the working directory of the created process
 * @param async
 *            tells if the command should be run asynchronously (in a
 *            separate thread)
 * @param stdoutConsumer
 *            consumes the standard output stream as lines of characters
 * @param endConsumer
 *            called when the process actually ends
 * @param errorHandler
 *            upcalled when the command does not terminate successfully
 * @param args
 *            the command-line arguments
 * @return the process that was created to execute the command (can be still
 *         running at this point if <code>async</code> is <code>true</code>)
 */
public static Process runCommand(String command, File directory, boolean async, Consumer<String> stdoutConsumer,
        Consumer<Process> endConsumer, Runnable errorHandler, String... args) {

    String[] cmd;
    if (System.getProperty("os.name").startsWith("Windows")) {
        if (nodeCommands.contains(command)) {
            cmd = new String[] { getNpmPath(command) };
        } else {
            cmd = new String[] { "cmd", "/c", command };
        }
    } else {
        if (nodeCommands.contains(command)) {
            cmd = new String[] { getNpmPath(command) };
        } else {
            cmd = new String[] { command };
        }
    }
    cmd = ArrayUtils.addAll(cmd, args);

    logger.debug("run command: " + StringUtils.join(cmd, " "));
    Process[] process = { null };
    try {
        ProcessBuilder processBuilder = new ProcessBuilder(cmd);
        processBuilder.redirectErrorStream(true);
        if (directory != null) {
            processBuilder.directory(directory);
        }
        if (!StringUtils.isBlank(EXTRA_PATH)) {
            processBuilder.environment().put("PATH",
                    processBuilder.environment().get("PATH") + File.pathSeparator + EXTRA_PATH);
        }

        process[0] = processBuilder.start();

        Runnable runnable = new Runnable() {

            @Override
            public void run() {
                try {
                    try (BufferedReader in = new BufferedReader(
                            new InputStreamReader(process[0].getInputStream()))) {
                        String line;
                        while ((line = in.readLine()) != null) {
                            if (stdoutConsumer != null) {
                                stdoutConsumer.accept(line);
                            } else {
                                logger.info(command + " - " + line);
                            }
                        }
                    }

                    process[0].waitFor();
                    if (endConsumer != null) {
                        endConsumer.accept(process[0]);
                    }
                    if (process[0].exitValue() != 0) {
                        if (errorHandler != null) {
                            errorHandler.run();
                        }
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                    if (errorHandler != null) {
                        errorHandler.run();
                    }
                }
            }
        };
        if (async) {
            new Thread(runnable).start();
        } else {
            runnable.run();
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        if (errorHandler != null) {
            errorHandler.run();
        }
        return null;
    }
    return process[0];
}

From source file:azkaban.utils.FileIOUtils.java

/**
 * Run a unix command that will symlink files, and recurse into directories.
 *//*from   www  . jav  a2s  . c o m*/
public static void createDeepSymlink(File sourceDir, File destDir) throws IOException {
    if (!sourceDir.exists()) {
        throw new IOException("Source directory " + sourceDir.getPath() + " doesn't exist");
    } else if (!destDir.exists()) {
        throw new IOException("Destination directory " + destDir.getPath() + " doesn't exist");
    } else if (sourceDir.isFile() && destDir.isFile()) {
        throw new IOException("Source or Destination is not a directory.");
    }

    Set<String> paths = new HashSet<String>();
    createDirsFindFiles(sourceDir, sourceDir, destDir, paths);

    StringBuffer buffer = new StringBuffer();
    for (String path : paths) {
        File sourceLink = new File(sourceDir, path);
        path = "." + path;

        buffer.append("ln -s ").append(sourceLink.getAbsolutePath()).append("/*").append(" ").append(path)
                .append(";");
    }

    String command = buffer.toString();
    ProcessBuilder builder = new ProcessBuilder().command("sh", "-c", command);
    builder.directory(destDir);

    // XXX what about stopping threads ??
    Process process = builder.start();
    try {
        NullLogger errorLogger = new NullLogger(process.getErrorStream());
        NullLogger inputLogger = new NullLogger(process.getInputStream());
        errorLogger.start();
        inputLogger.start();

        try {
            if (process.waitFor() < 0) {
                // Assume that the error will be in standard out. Otherwise it'll be
                // in standard in.
                String errorMessage = errorLogger.getLastMessages();
                if (errorMessage.isEmpty()) {
                    errorMessage = inputLogger.getLastMessages();
                }

                throw new IOException(errorMessage);
            }

            // System.out.println(errorLogger.getLastMessages());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    } finally {
        IOUtils.closeQuietly(process.getInputStream());
        IOUtils.closeQuietly(process.getOutputStream());
        IOUtils.closeQuietly(process.getErrorStream());
    }
}

From source file:elh.eus.absa.NLPpipelineWrapper.java

public static int eustaggerCall(String taggerCommand, String string, String fname) {

    try {/*from   w ww  .  j av  a2s.  c  o  m*/
        File temp = new File(fname);
        //System.err.println("eustaggerCall: created temp file: "+temp.getAbsolutePath());
        BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
        bw.write(string + "\n");
        bw.close();

        String[] command = { taggerCommand, temp.getName() };
        System.err.println("Eustagger agindua: " + Arrays.toString(command));

        ProcessBuilder eustBuilder = new ProcessBuilder().command(command);
        eustBuilder.directory(new File(temp.getParent()));
        //.redirectErrorStream(true);
        Process eustagger = eustBuilder.start();
        int success = eustagger.waitFor();
        //System.err.println("eustagger succesful? "+success);
        if (success != 0) {
            System.err.println("eustaggerCall: eustagger error");
        } else {
            String tagged = fname + ".kaf";
            BufferedReader reader = new BufferedReader(new InputStreamReader(eustagger.getInputStream()));
            //new Eustagger_lite outputs to stdout. Also called ixa-pipe-pos-eu
            if (taggerCommand.contains("eustagger") || taggerCommand.contains("ixa-pipe")) {
                Files.copy(eustagger.getInputStream(), Paths.get(tagged));
            }
            // old eustagger (euslem)
            else {
                FileUtilsElh.renameFile(temp.getAbsolutePath() + ".etiketatua3", tagged);
            }
        }
        //
        // delete all temporal files used in the process.
        temp.delete();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return -1;
    }

    return 0;
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call Rtrace to run the simulation//from  w w  w .j  a v a2s . c  o m
 * @param config Radiance Configuration
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param args
 * @param model
 * @param in
 * @param out
 * @param err
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runRtrace(RadianceConfig config, String WorkDir, String args, String model, String in,
        String out, String err, ProcessWrapper process) {

    int ExitValue = -99;

    try {
        StringBuilder buf = new StringBuilder(config.getResolvedRadianceBinDir());
        buf.append(File.separator).append("rtrace");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        String[] arglist = args.split("\\s+");
        command.addAll(Arrays.asList(arglist));
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir());
        builder.redirectError(new File(WorkDir + File.separator + err));
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        builder.redirectInput(new File(WorkDir + File.separator + in));

        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing Rtrace", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSUtil.java

public static void executeCommand(FileObject workingFolder, ProgressHandler handler, String... command) {
    try {//from   ww  w.j  a va  2s.co  m
        ProcessBuilder pb = new ProcessBuilder(command);

        //                Map<String, String> env = pb.environment();
        // If you want clean environment, call env.clear() first
        //                env.put("VAR1", "myValue");
        //                env.remove("OTHERVAR");
        //                env.put("VAR2", env.get("VAR1") + "suffix");
        pb.directory(FileUtil.toFile(workingFolder));
        Process proc = pb.start();
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

        // read the output from the command
        String s;
        while ((s = stdInput.readLine()) != null) {
            handler.append(Console.wrap(s, FG_BLUE));
        }

        // read any errors from the attempted command
        while ((s = stdError.readLine()) != null) {
            handler.append(Console.wrap(s, FG_DARK_RED));
        }
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
    }
}

From source file:jeplus.RadianceWinTools.java

/**
 * Call DaySim gen_dc to run the simulation
 * @param config Radiance Configuration/*from  w w  w  . j a  va2s.  c  om*/
 * @param WorkDir The working directory where the input files are stored and the output files to be generated
 * @param model
 * @param in
 * @param out
 * @param err
 * @param process
 * @return the result code represents the state of execution steps. >=0 means successful
 */
public static int runGen_DC(RadianceConfig config, String WorkDir, String model, String in, String out,
        String err, ProcessWrapper process) {

    int ExitValue = -99;

    // Manipulate header file
    HashMap<String, String> props = new HashMap<>();
    // props.put("project_name", "");
    props.put("project_directory", "./");
    props.put("bin_directory", config.getResolvedDaySimBinDir());
    props.put("tmp_directory", "./");
    props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/");
    props.put("sensor_file", in);
    try {
        FileUtils.moveFile(new File(WorkDir + File.separator + model),
                new File(WorkDir + File.separator + model + ".ori"));
    } catch (IOException ex) {
        logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex);
    }
    DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model,
            props);

    // Run command
    try {
        StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir());
        buf.append(File.separator).append("gen_dc");

        List<String> command = new ArrayList<>();
        command.add(buf.toString());
        command.add(model);
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(new File(WorkDir));
        builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir());
        builder.redirectOutput(new File(WorkDir + File.separator + out));
        if (err == null || out.equals(err)) {
            builder.redirectErrorStream(true);
        } else {
            builder.redirectError(new File(WorkDir + File.separator + err));
        }
        if (in != null) {
            builder.redirectInput(new File(WorkDir + File.separator + in));
        }
        Process proc = builder.start();
        if (process != null) {
            process.setWrappedProc(proc);
        }
        ExitValue = proc.waitFor();
    } catch (IOException | InterruptedException ex) {
        logger.error("Error occoured when executing DaySim gen_dc", ex);
    }

    // Return Radiance exit value
    return ExitValue;
}

From source file:com.tascape.qa.th.Utils.java

public static Process cmd(String[] commands, final File file, final File workingDir,
        final String... ignoreRegex) throws IOException {
    FileUtils.touch(file);/* w  w w .ja v  a 2  s  .c om*/
    LOG.debug("Saving console output to {}", file.getAbsolutePath());

    ProcessBuilder pb = new ProcessBuilder(commands);
    pb.redirectErrorStream(true);
    pb.directory(workingDir);
    LOG.info("Running command {}:  {}", workingDir == null ? "" : workingDir.getAbsolutePath(),
            pb.command().toString().replaceAll(",", ""));
    final Process p = pb.start();

    Thread t = new Thread(Thread.currentThread().getName() + "-" + p.hashCode()) {
        @Override
        public void run() {
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String console = "console-" + stdIn.hashCode();
            try (PrintWriter pw = new PrintWriter(file)) {
                for (String line = stdIn.readLine(); line != null;) {
                    LOG.trace("{}: {}", console, line);
                    if (null == ignoreRegex || ignoreRegex.length == 0) {
                        pw.println(line);
                    } else {
                        boolean ignore = false;
                        for (String regex : ignoreRegex) {
                            if (!regex.isEmpty() && (line.contains(regex) || line.matches(regex))) {
                                ignore = true;
                                break;
                            }
                        }
                        if (!ignore) {
                            pw.println(line);
                        }
                    }
                    pw.flush();
                    line = stdIn.readLine();
                }
            } catch (IOException ex) {
                LOG.warn(ex.getMessage());
            }
            LOG.trace("command is done");
        }
    };
    t.setDaemon(true);
    t.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (p != null) {
                p.destroy();
            }
        }
    });
    return p;
}

From source file:com.tascape.qa.th.Utils.java

/**
 * Executes command, and waits for the expected pass/fail phrase in console printout within timeout,
 *
 * @param command    command line/*from w  w w .  ja v a 2s  .  c o  m*/
 * @param pass       skip checking if null
 * @param fail       skip checking if null
 * @param timeout    set 0 for not to check the output message, otherwise, waiting for timeout
 * @param workingDir working directory
 *
 * @return console output as a list of strings
 *
 * @throws IOException          for command error
 * @throws InterruptedException when interrupted
 */
public static List<String> cmd(String[] command, final String pass, final String fail, final long timeout,
        final String workingDir) throws IOException, InterruptedException {
    ProcessBuilder pb = new ProcessBuilder(command);
    if (workingDir != null) {
        pb.directory(new File(workingDir));
    }
    pb.redirectErrorStream(true);
    LOG.debug("Running command: " + pb.command().toString().replace(",", ""));
    final Process p = pb.start();
    Thread thread;
    final List<String> output = new ArrayList<>();

    if (timeout == 0) {
        LOG.debug("This is a start-and-exit command");
        output.add(PASS);
        return output;
    } else {
        thread = new Thread() {
            @Override
            public void run() {
                try {
                    LOG.debug("Command timeouts in {} ms", timeout);
                    Thread.sleep(timeout);
                    try {
                        p.exitValue();
                    } catch (IllegalThreadStateException ex) {
                        LOG.debug("killing subprocess {} - {}", p, ex.getMessage());
                        p.destroy();
                    }
                } catch (InterruptedException ex) {
                    LOG.warn(ex.getMessage());
                }
            }
        };
        thread.setName(Thread.currentThread().getName() + "-" + p.hashCode());
        thread.setDaemon(true);
        thread.start();
    }

    BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String c = p + " - ";
    for (String line = stdIn.readLine(); line != null;) {
        LOG.trace("{}{}", c, line);
        output.add(line);
        try {
            line = stdIn.readLine();
        } catch (IOException ex) {
            LOG.warn(ex.getMessage());
            break;
        }
    }
    LOG.debug("Command exit code {}", p.waitFor());
    thread.interrupt();
    try {
        stdIn.close();
    } catch (IOException ex) {
        LOG.warn("", ex);
    }

    for (String s : output) {
        if (pass != null && (s.contains(pass) || s.matches(pass))) {
            output.add(PASS);
            break;
        } else if (fail != null && s.contains(fail)) {
            output.add(FAIL);
            break;
        }
    }
    return output;
}

From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java

public static String runCliCommands(File cliExecutablePath, List<List<String>> commands, boolean isDebug)
        throws IOException, InterruptedException {
    if (!cliExecutablePath.isFile()) {
        throw new IllegalArgumentException(cliExecutablePath + " is not a file");
    }//w  ww .ja v a 2 s.c om

    File workingDirectory = cliExecutablePath.getAbsoluteFile().getParentFile();
    if (!workingDirectory.isDirectory()) {
        throw new IllegalArgumentException(workingDirectory + " is not a directory");
    }

    int argsCount = 0;
    for (List<String> command : commands) {
        argsCount += command.size();
    }

    // needed to properly intercept error return code
    String[] cmd = new String[(argsCount == 0 ? 0 : 1) + 4 /* cmd /c call cloudify.bat ["args"] */];
    int i = 0;
    cmd[i] = "cmd";
    i++;
    cmd[i] = "/c";
    i++;
    cmd[i] = "call";
    i++;
    cmd[i] = cliExecutablePath.getAbsolutePath();
    i++;
    if (argsCount > 0) {
        cmd[i] = "\"";
        //TODO: Use StringBuilder
        for (List<String> command : commands) {
            if (command.size() > 0) {
                for (String arg : command) {
                    if (cmd[i].length() > 0) {
                        cmd[i] += " ";
                    }
                    cmd[i] += arg;
                }
                cmd[i] += ";";
            }
        }
        cmd[i] += "\"";
    }
    final ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(workingDirectory);
    pb.redirectErrorStream(true);

    String extCloudifyJavaOptions = "";

    if (isDebug) {
        extCloudifyJavaOptions += "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000 -Xnoagent -Djava.compiler=NONE";
    }

    pb.environment().put("EXT_CLOUDIFY_JAVA_OPTIONS", extCloudifyJavaOptions);
    final StringBuilder sb = new StringBuilder();

    logger.info("running: " + cliExecutablePath + " " + Arrays.toString(cmd));

    // log std output and redirected std error
    Process p = pb.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = reader.readLine();
    while (line != null) {
        sb.append(line).append("\n");
        line = reader.readLine();
        logger.info(line);
    }

    final String readResult = sb.toString();
    final int exitValue = p.waitFor();

    logger.info("Exit value = " + exitValue);
    if (exitValue != 0) {
        Assert.fail("Cli ended with error code: " + exitValue);
    }
    return readResult;
}