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:jenkins.plugins.asqatasun.AsqatasunRunner.java

public void callService() throws IOException, InterruptedException {
    File logFile = AsqatasunRunnerBuilder.createTempFile(contextDir, "log-" + new Random().nextInt() + ".log",
            "");/*from w  ww  .  jav  a 2s  .  c o  m*/
    File scenarioFile = AsqatasunRunnerBuilder.createTempFile(contextDir, scenarioName + "_#" + buildNumber,
            AsqatasunRunnerBuilder.forceVersion1ToScenario(scenario));

    ProcessBuilder pb = new ProcessBuilder(tgScriptName, "-f", firefoxPath, "-r", referential, "-l", level,
            "-d", displayPort, "-x", xmxValue, "-o", logFile.getAbsolutePath(), "-t", "Scenario",
            scenarioFile.getAbsolutePath());

    pb.directory(contextDir);
    pb.redirectErrorStream(true);
    listener.getLogger().print("Launching asqatasun runner with the following options : ");
    listener.getLogger().print(pb.command());
    Process p = pb.start();
    p.waitFor();

    extractDataAndPrintOut(logFile, listener.getLogger());

    if (!isDebug) {
        FileUtils.forceDelete(logFile);
    }

    FileUtils.forceDelete(scenarioFile);
}

From source file:com.moss.appsnap.keeper.windows.MSWindowsAppHandler.java

@Override
public void launch() {
    InstallableId id = info.currentVersion();
    if (id == null) {
        throw new NullPointerException("There is no current version for " + info.id());
    }/* w w  w  .  j av a  2s.  com*/
    ResolvedJavaLaunchSpec rls = guts.data.javaLaunchSpecs.get(id);

    StringBuilder line = launchCommand(rls);

    try {
        Process p;
        if (info.isKeeperSoftware()) {

            //            System.out.println("Using line: " + line);
            //            String regex = "\"";
            //            String replacement = "\\\\\"";
            //            String arg = line.toString().replaceAll(regex, replacement);
            //            System.out.println("Using arg: " + arg);
            ProcessBuilder pb = new ProcessBuilder(daemonLauncherExe.getAbsolutePath());
            pb.directory(installDirPath);
            p = pb.start();

        } else {
            p = Runtime.getRuntime().exec(line.toString());
        }

        new MonitorThread(p).start();
    } catch (IOException e) {
        e.printStackTrace();
        JOptionPane.showMessageDialog(null,
                "Launch error: " + e.getClass().getSimpleName() + ": " + e.getMessage());
    }
    //      JOptionPane.showMessageDialog(null, "ERROR: NOT YET IMPLEMENTED");
}

From source file:org.nuxeo.ecm.platform.commandline.executor.service.executors.ShellExecutor.java

protected ExecResult exec1(CommandLineDescriptor cmdDesc, CmdParameters params, EnvironmentDescriptor env)
        throws IOException {
    // split the configured parameters while keeping quoted parts intact
    List<String> list = new ArrayList<>();
    list.add(cmdDesc.getCommand());//from   ww w . ja va2 s  .c o  m
    Matcher m = COMMAND_SPLIT.matcher(cmdDesc.getParametersString());
    while (m.find()) {
        String word;
        if (m.group(1) != null) {
            word = m.group(1); // double-quoted
        } else if (m.group(2) != null) {
            word = m.group(2); // single-quoted
        } else {
            word = m.group(); // word
        }
        List<String> words = replaceParams(word, params);
        list.addAll(words);
    }

    List<Process> processes = new LinkedList<>();
    List<Thread> pipes = new LinkedList<>();
    List<String> command = new LinkedList<>();
    Process process = null;
    for (Iterator<String> it = list.iterator(); it.hasNext();) {
        String word = it.next();
        boolean build;
        if (word.equals("|")) {
            build = true;
        } else {
            // on Windows, look up the command in the PATH first
            if (command.isEmpty() && SystemUtils.IS_OS_WINDOWS) {
                command.add(getCommandAbsolutePath(word));
            } else {
                command.add(word);
            }
            build = !it.hasNext();
        }
        if (!build) {
            continue;
        }
        ProcessBuilder processBuilder = new ProcessBuilder(command);
        command = new LinkedList<>(); // reset for next loop
        processBuilder.directory(new File(env.getWorkingDirectory()));
        processBuilder.environment().putAll(env.getParameters());
        processBuilder.redirectErrorStream(true);
        Process newProcess = processBuilder.start();
        processes.add(newProcess);
        if (process == null) {
            // first process, nothing to input
            IOUtils.closeQuietly(newProcess.getOutputStream());
        } else {
            // pipe previous process output into new process input
            // needs a thread doing the piping because Java has no way to connect two children processes directly
            // except through a filesystem named pipe but that can't be created in a portable manner
            Thread pipe = pipe(process.getInputStream(), newProcess.getOutputStream());
            pipes.add(pipe);
        }
        process = newProcess;
    }

    // get result from last process
    @SuppressWarnings("null")
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;
    List<String> output = new ArrayList<>();
    while ((line = reader.readLine()) != null) {
        output.add(line);
    }
    reader.close();

    // wait for all processes, get first non-0 exit status
    int returnCode = 0;
    for (Process p : processes) {
        try {
            int exitCode = p.waitFor();
            if (returnCode == 0) {
                returnCode = exitCode;
            }
        } catch (InterruptedException e) {
            ExceptionUtils.checkInterrupt(e);
        }
    }

    // wait for all pipes
    for (Thread t : pipes) {
        try {
            t.join();
        } catch (InterruptedException e) {
            ExceptionUtils.checkInterrupt(e);
        }
    }

    return new ExecResult(null, output, 0, returnCode);
}

From source file:facs.utils.Billing.java

/**
 * creates temporary tex file and executes pdflatex in order to create the final pdf file WARNING:
 * Be sure that you have set all parameters before executing that method. Otherwise you will get a
 * apache velocity error./* w w  w  .  j  ava2s .c om*/
 * 
 * @return
 * @throws IOException
 * @throws InterruptedException
 */
public File createPdf() throws IOException, InterruptedException {
    if (!tempTexFile.exists()) {
        tempTexFile.createNewFile();
    }
    FileWriter fw = new FileWriter(tempTexFile.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    template.merge(context, bw);
    bw.close();

    List<String> cmd = new ArrayList<String>(
            Arrays.asList(pdflatexPath, "-interaction=nonstopmode", tempTexFile.getName()));
    String basename = FilenameUtils.getBaseName(tempTexFile.getName());

    String fileNamme = basename + ".pdf";
    File resultFile = Paths.get(tempTexFile.getParent(), fileNamme).toFile();
    // Runtime rt = Runtime.getRuntime();
    // Process p = rt.exec(cmd);
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(tempTexFile.getParentFile());
    System.out.println("Basename: " + basename + " fileNamme: " + fileNamme);
    Process p = pb.start();

    int exitValue = p.waitFor();
    if (exitValue != 0 && !resultFile.exists()) {
        StringBuffer sb = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        System.out.println(sb.toString());

        // TODO There is for sure a better exception to say that pdflatex failed?
        throw new FileNotFoundException("result file " + resultFile.getAbsolutePath() + "does not exist.");
    } else {
        return resultFile;
    }
}

From source file:edu.umn.msi.tropix.common.execution.process.impl.ProcessFactoryImpl.java

public Process createProcess(final ProcessConfiguration processConfiguration) {
    final List<String> command = new LinkedList<String>();
    final String application = processConfiguration.getApplication();
    Preconditions.checkNotNull(application, "Attempted to create process with null application.");
    command.add(application);/*  w  ww .java 2  s  .  c  o  m*/
    final List<String> arguments = processConfiguration.getArguments();
    if (arguments != null) {
        command.addAll(processConfiguration.getArguments());
    }
    LOG.trace("Creating process builder with commands " + Joiner.on(" ").join(command) + " in directory "
            + processConfiguration.getDirectory());
    final ProcessBuilder processBuilder = new ProcessBuilder(command);
    if (processConfiguration.getEnvironment() != null) {
        for (final Entry<String, String> entry : processConfiguration.getEnvironment().entrySet()) {
            processBuilder.environment().put(entry.getKey(), entry.getValue());
        }
    }
    processBuilder.directory(processConfiguration.getDirectory());

    java.lang.Process baseProcess = null;
    try {
        baseProcess = processBuilder.start();
    } catch (final IOException e) {
        throw new IllegalStateException(
                "Failed to start process corresponding to process configuration " + processConfiguration, e);
    }
    final ProcessImpl process = new ProcessImpl();
    process.setBaseProcess(baseProcess);
    return process;
}

From source file:edu.isi.wings.execution.engine.api.impl.distributed.DistributedExecutionEngine.java

@Override
public ProcessStatus call() throws Exception {
    File tempdir = File.createTempFile(planName + "-", "-" + exeName);
    if (!tempdir.delete() || !tempdir.mkdirs())
        throw new Exception("Cannot create temp directory");

    ProcessStatus status = new ProcessStatus();
    try {// w w w .  j av a 2 s  .co  m
        File codef = new File(this.codeBinary);
        codef.setExecutable(true);

        PrintWriter fout = null;
        if (outfilepath != null) {
            File f = new File(outfilepath);
            f.getParentFile().mkdirs();
            fout = new PrintWriter(f);
        }

        ProcessBuilder pb = new ProcessBuilder(args);
        pb.directory(tempdir);
        pb.redirectErrorStream(true);

        // Set environment variables
        for (String var : this.environment.keySet())
            pb.environment().put(var, this.environment.get(var));

        this.process = pb.start();

        // Read output stream
        StreamGobbler outputGobbler = new StreamGobbler(this.process.getInputStream(), fout);
        outputGobbler.start();

        // Wait for the process to exit
        this.process.waitFor();

        status.setExitValue(this.process.exitValue());
        status.setLog(outputGobbler.getLog());
    } catch (InterruptedException e) {
        if (this.process != null) {
            //System.out.println("Stopping remote process");
            this.process.destroy();
        }
        status.setLog("!! Stopping Remotely !! .. " + exeName);
        status.setExitValue(-1);
    } catch (Exception e) {
        status.setLog(e.getMessage());
        status.setExitValue(-1);
    }

    // Delete temp directory
    FileUtils.deleteDirectory(tempdir);
    return status;
}

From source file:com.skcraft.launcher.launch.Runner.java

@Override
public Process call() throws Exception {
    if (!instance.isInstalled()) {
        throw new LauncherException("Update required", _("runner.updateRequired"));
    }//www .  j  a va 2 s .com

    config = launcher.getConfig();
    builder = new JavaProcessBuilder();
    assetsRoot = launcher.getAssets();

    // Load manifiests
    versionManifest = mapper.readValue(instance.getVersionPath(), VersionManifest.class);

    // Load assets index
    File assetsFile = assetsRoot.getIndexPath(versionManifest);
    try {
        assetsIndex = mapper.readValue(assetsFile, AssetsIndex.class);
    } catch (FileNotFoundException e) {
        instance.setInstalled(false);
        Persistence.commitAndForget(instance);
        throw new LauncherException("Missing assets index " + assetsFile.getAbsolutePath(),
                _("runner.missingAssetsIndex", instance.getTitle(), assetsFile.getAbsolutePath()));
    } catch (IOException e) {
        instance.setInstalled(false);
        Persistence.commitAndForget(instance);
        throw new LauncherException("Corrupt assets index " + assetsFile.getAbsolutePath(),
                _("runner.corruptAssetsIndex", instance.getTitle(), assetsFile.getAbsolutePath()));
    }

    // Copy over assets to the tree
    try {
        AssetsRoot.AssetsTreeBuilder assetsBuilder = assetsRoot.createAssetsBuilder(versionManifest);
        progress = assetsBuilder;
        virtualAssetsDir = assetsBuilder.build();
    } catch (LauncherException e) {
        instance.setInstalled(false);
        Persistence.commitAndForget(instance);
        throw e;
    }

    progress = new DefaultProgress(0.9, _("runner.collectingArgs"));

    addJvmArgs();
    addLibraries();
    addJarArgs();
    addProxyArgs();
    addWindowArgs();
    addPlatformArgs();

    builder.classPath(getJarPath());
    builder.setMainClass(versionManifest.getMainClass());

    callLaunchModifier();

    ProcessBuilder processBuilder = new ProcessBuilder(builder.buildCommand());
    processBuilder.directory(instance.getContentDir());
    Runner.log.info("Launching: " + builder);
    checkInterrupted();

    progress = new DefaultProgress(1, _("runner.startingJava"));

    return processBuilder.start();
}

From source file:org.codelibs.fess.screenshot.impl.CommandGenerator.java

@Override
public void generate(final String url, final File outputFile) {
    if (logger.isDebugEnabled()) {
        logger.debug("Generate ScreenShot: " + url);
    }/*from ww w .j ava 2s .co m*/

    if (outputFile.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug("The screenshot file exists: " + outputFile.getAbsolutePath());
        }
        return;
    }

    final File parentFile = outputFile.getParentFile();
    if (!parentFile.exists()) {
        parentFile.mkdirs();
    }
    if (!parentFile.isDirectory()) {
        logger.warn("Not found: " + parentFile.getAbsolutePath());
        return;
    }

    final String outputPath = outputFile.getAbsolutePath();
    final List<String> cmdList = new ArrayList<>();
    for (final String value : commandList) {
        cmdList.add(value.replace("${url}", url).replace("${outputFile}", outputPath));
    }

    ProcessBuilder pb = null;
    Process p = null;

    if (logger.isDebugEnabled()) {
        logger.debug("ScreenShot Command: " + cmdList);
    }

    TimerTask task = null;
    try {
        pb = new ProcessBuilder(cmdList);
        pb.directory(baseDir);
        pb.redirectErrorStream(true);

        p = pb.start();

        task = new ProcessDestroyer(p, cmdList);
        try {
            destoryTimer.schedule(task, commandTimeout);

            String line;
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.defaultCharset()));
                while ((line = br.readLine()) != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(line);
                    }
                }
            } finally {
                IOUtils.closeQuietly(br);
            }

            p.waitFor();
        } catch (final Exception e) {
            p.destroy();
        }
    } catch (final Exception e) {
        logger.warn("Failed to generate a screenshot of " + url, e);
    }
    if (task != null) {
        task.cancel();
        task = null;
    }

    if (outputFile.isFile() && outputFile.length() == 0) {
        logger.warn("ScreenShot File is empty. URL is " + url);
        if (outputFile.delete()) {
            logger.info("Deleted: " + outputFile.getAbsolutePath());
        }
    }

    if (logger.isDebugEnabled()) {
        logger.debug("ScreenShot File: " + outputPath);
    }
}

From source file:org.codelibs.fess.thumbnail.impl.CommandGenerator.java

protected void executeCommand(final String thumbnailId, final List<String> cmdList) {
    ProcessBuilder pb = null;
    Process p = null;//from   w  w w.  j  av  a2 s.  c o m

    if (logger.isDebugEnabled()) {
        logger.debug("Thumbnail Command: " + cmdList);
    }

    TimerTask task = null;
    try {
        pb = new ProcessBuilder(cmdList);
        pb.directory(baseDir);
        pb.redirectErrorStream(true);

        p = pb.start();

        task = new ProcessDestroyer(p, cmdList);
        try {
            destoryTimer.schedule(task, commandTimeout);

            String line;
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(p.getInputStream(), Charset.defaultCharset()));
                while ((line = br.readLine()) != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(line);
                    }
                }
            } finally {
                IOUtils.closeQuietly(br);
            }

            p.waitFor();
        } catch (final Exception e) {
            p.destroy();
        }
    } catch (final Exception e) {
        logger.warn("Failed to generate a thumbnail of " + thumbnailId, e);
    }
    if (task != null) {
        task.cancel();
        task = null;
    }
}

From source file:gr.aueb.dmst.istlab.unixtools.actions.impl.ExecuteCustomCommandAction.java

@Override
public void execute(ActionExecutionCallback<DataActionResult<InputStream>> callback)
        throws IOException, InterruptedException {
    DataActionResult<InputStream> result;
    List<String> arguments = EclipsePluginUtil.getSystemShellInfo();

    ProcessBuilder pb;

    if (SystemUtils.IS_OS_WINDOWS) {
        pb = new ProcessBuilder(arguments.get(0), arguments.get(1), arguments.get(2) + "\"cd "
                + this.commandToExecute.getShellDirectory() + ";" + this.commandToExecute.getCommand() + "\"");
    } else {/*from   ww w .j  a v a 2s.  co m*/
        arguments.add(this.commandToExecute.getCommand());
        pb = new ProcessBuilder(arguments);
        pb.directory(new File(this.commandToExecute.getShellDirectory()));
    }
    pb.redirectErrorStream(true);

    Process p;
    try {
        p = pb.start();
        p.waitFor();
        InputStream cmdStream = p.getInputStream();
        result = new DataActionResult<>(cmdStream);
    } catch (IOException e) {
        logger.fatal("IO problem occurred while executing the command");
        result = new DataActionResult<>(e);
        throw new IOException(e);
    } catch (InterruptedException e) {
        logger.fatal("The current thread has been interrupted while executing the command");
        result = new DataActionResult<>(e);
        throw new InterruptedException();
    }

    callback.onCommandExecuted(result);
}