Example usage for java.lang ProcessBuilder command

List of usage examples for java.lang ProcessBuilder command

Introduction

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

Prototype

List command

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

Click Source Link

Usage

From source file:org.craftercms.cstudio.publishing.processor.ShellProcessor.java

@Override
public void doProcess(PublishedChangeSet changeSet, Map<String, String> parameters, PublishingTarget target)
        throws PublishingException {
    checkConfiguration(parameters, target);
    LOGGER.debug("Starting Shell Processor");
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(getWorkingDir(workingDir, parameters.get(FileUploadServlet.PARAM_SITE)));
    LOGGER.debug("Working directory is " + workingDir);
    HashMap<String, String> argumentsMap = buildArgumentsMap(getFileList(parameters, changeSet));
    if (asSingleCommand) {
        StrSubstitutor substitutor = new StrSubstitutor(argumentsMap, "%{", "}");
        String execComand = substitutor.replace(command);
        LOGGER.debug("Command to be Executed is " + execComand);
        builder.command("/bin/bash", "-c", execComand);

    } else {//from w  ww.j  a v  a2 s . c om
        Set<String> keys = argumentsMap.keySet();
        ArrayList<String> commandAsList = new ArrayList<String>();
        commandAsList.add(command.trim());
        for (String key : keys) {
            if (!key.equalsIgnoreCase(INCLUDE_FILTER_PARAM)) {
                commandAsList.add(argumentsMap.get(key));
            }
        }
        LOGGER.debug("Command to be Executed is " + StringUtils.join(commandAsList, " "));
        builder.command(commandAsList);
    }

    builder.environment().putAll(enviroment);
    builder.redirectErrorStream(true);
    try {
        Process process = builder.start();
        process.waitFor();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String str;
        while ((str = reader.readLine()) != null) {
            LOGGER.info("PROCESS OUTPUT :" + str);
        }
        reader.close();
        LOGGER.info("Process Finish with Exit Code " + process.exitValue());
        LOGGER.debug("Process Output ");
    } catch (IOException ex) {
        LOGGER.error("Error ", ex);
    } catch (InterruptedException e) {
        LOGGER.error("Error ", e);
    } finally {
        LOGGER.debug("End of Shell Processor");
    }
}

From source file:functionaltests.scilab.AbstractScilabTest.java

protected ProcessBuilder initCommand(String testName, int nb_iter) throws Exception {
    ProcessBuilder pb = new ProcessBuilder();
    pb.directory(sci_tb_home);// w  w  w.  j a  v  a  2 s.  c o  m
    pb.redirectErrorStream(true);
    int runAsMe = 0;

    if (System.getProperty("proactive.test.runAsMe") != null) {
        runAsMe = 1;
    }
    if (System.getProperty("scilab.test.leaks") != null) {
        testLeak = 1;
        leakFile = new File(test_home + fs + "JIMS.log");
        if (leakFile.exists()) {
            leakFile.delete();
        }
    }
    if (System.getProperty("scilab.bin.path") != null) {
        pb.command(System.getProperty("scilab.bin.path"), "-nw", "-f",
                (new File(test_home + fs + "RunUnitTest.sci")).getCanonicalPath(), "-args", schedURI.toString(),
                credFile.toString(), "" + nb_iter, testName, "" + runAsMe, "" + testLeak, "" + leakFile);
    } else {
        pb.command("scilab", "-nw", "-f", (new File(test_home + fs + "RunUnitTest.sci")).getCanonicalPath(),
                "-args", schedURI.toString(), credFile.toString(), "" + nb_iter, testName, "" + runAsMe,
                "" + testLeak, "" + leakFile);
    }
    return pb;
}

From source file:org.apache.pulsar.functions.runtime.ProcessRuntime.java

private void startProcess() {
    deathException = null;/*from  www . j a  v  a  2 s. c o m*/
    try {
        ProcessBuilder processBuilder = new ProcessBuilder(processArgs).inheritIO();
        if (StringUtils.isNotEmpty(extraDependenciesDir)) {
            processBuilder.environment().put("PYTHONPATH", "${PYTHONPATH}:" + extraDependenciesDir);
        }
        secretsProviderConfigurator.configureProcessRuntimeSecretsProvider(processBuilder,
                instanceConfig.getFunctionDetails());
        log.info("ProcessBuilder starting the process with args {}",
                String.join(" ", processBuilder.command()));
        process = processBuilder.start();
    } catch (Exception ex) {
        log.error("Starting process failed", ex);
        deathException = ex;
        return;
    }
    try {
        int exitValue = process.exitValue();
        log.error("Instance Process quit unexpectedly with return value " + exitValue);
        tryExtractingDeathException();
    } catch (IllegalThreadStateException ex) {
        log.info("Started process successfully");
    }
}

From source file:maltcms.ui.nb.pipelineRunner.ui.MaltcmsLocalHostExecution.java

@Override
public File call() throws Exception {
    getProgressHandle().setDisplayName("Running Maltcms...");
    getProgressHandle().start();//from  w  w w. j  a v  a 2 s.  c  o m
    outputDir = createOutputDirectory();
    final ProcessBuilder pb = new ProcessBuilder(buildCommandLine());
    String location = NbPreferences.forModule(PipelineRunnerTopComponent.class).get("maltcmsInstallationPath",
            "NA");
    if (location.equals("NA")) {
        throw new IllegalArgumentException("Please set maltcms location under settings!");
    }
    File f = new File(location);
    pb.directory(f);
    Logger.getLogger(MaltcmsLocalHostExecution.class.getName()).log(Level.FINE,
            "Process: {0} workingDirectory: {1}", new Object[] { pb.command(), pb.directory() });
    pb.redirectErrorStream(true);
    InputOutput io = IOProvider.getDefault().getIO("Running Maltcms in " + outputDir.getName(), false);
    //                io.setOutputVisible(true);
    FileObject outDir = FileUtil.toFileObject(outputDir);
    io.select();
    final OutputWriter writer = io.getOut();
    writer.reset();
    try {
        p = pb.start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            writer.println(line);
        }
        int ecode = p.waitFor();
        Logger.getLogger(MaltcmsLocalHostExecution.class.getName()).log(Level.WARNING,
                "Maltcms exited with code: {0}", ecode);
        if (ecode == 0) {
            //                File workflow = new File(outputDir, "workflow.xml");
            Collection<File> files = FileUtils.listFiles(outputDir, new String[] { "xml" }, true);
            if (files.isEmpty()) {
                getProgressHandle().finish();
                throw new IOException("Could not locate workflow.xml in " + outputDir);
            } else {
                File resultFile = null;
                for (File file : files) {
                    if (file.getName().equals("workflow.xml")) {
                        if (resultFile != null) {
                            throw new IllegalArgumentException(
                                    "Found more than one workflow.xml files below " + outputDir + "!");
                        }
                        resultFile = file;
                    }
                }
                if (resultFile != null) {
                    Logger.getLogger(MaltcmsLocalHostExecution.class.getName()).log(Level.FINE,
                            "Found result file: {0}", resultFile);
                    final File resFile = resultFile;
                    Runnable r = new Runnable() {
                        @Override
                        public void run() {
                            Project project;
                            try {
                                project = ProjectManager.getDefault()
                                        .findProject(FileUtil.toFileObject(resFile.getParentFile()));
                                if (project != null) {
                                    OpenProjects.getDefault().open(new Project[] { project }, false, true);
                                    TopComponent projWindow = WindowManager.getDefault()
                                            .findTopComponent("projectTabLogical_tc");
                                    projWindow.requestActive();
                                }
                            } catch (IOException | IllegalArgumentException ex) {
                                Exceptions.printStackTrace(ex);
                            }

                        }
                    };
                    SwingUtilities.invokeLater(r);
                    return resultFile;
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Exceptions.printStackTrace(ex);
    } finally {
        if (getProgressHandle() != null) {
            getProgressHandle().finish();
        }
    }
    return null;
}

From source file:org.eclipse.xtend.util.stdlib.SystemCommand.java

@Override
protected void invokeInternal(final WorkflowContext ctx, final ProgressMonitor monitor, final Issues issues) {
    try {//  w  w w  . j  a v  a2  s . co m
        int rc;
        final List<String> pbArgs = new ArrayList<String>();
        pbArgs.add(command);
        pbArgs.addAll(args);
        final ProcessBuilder pb = new ProcessBuilder(pbArgs);
        if (directory != null) {
            pb.directory(directory);
        }
        for (final String env : enventry) {
            final String[] keyvalue = env.split(",");
            pb.environment().put(keyvalue[0], keyvalue[1]);
        }
        if (inheritEnvironment) {
            log.debug("Inheriting system environment.");
            pb.environment().putAll(System.getenv());
        }
        if (log.isDebugEnabled()) {
            log.debug("Environment:");
            log.debug(pb.environment());
            log.debug(System.getenv());
        }
        log.info("Running command '" + pb.command() + "' in directory " + pb.directory().getAbsolutePath()
                + " ...");
        final Process p = pb.start();
        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

        String lineRead;
        while ((lineRead = br.readLine()) != null) {
            log.info(lineRead);
        }

        br = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        while ((lineRead = br.readLine()) != null) {
            log.error(lineRead);
        }
        rc = p.waitFor();
        if (rc != 0) {
            issues.addError("Error running '" + command + "'");
            return;
        }
        rc = p.exitValue();
        if (rc != 0) {
            issues.addError("Execution of command failed with error.");

        } else {
            log.info("Execution of command was successful.");
        }
    } catch (final Exception re) {
        issues.addError("Runtime error: " + re.getMessage());
    }
}

From source file:com.netflix.genie.agent.execution.statemachine.actions.SetUpJobAction.java

private File createJobEnvironmentFile(final File jobDirectory, final List<File> setUpFiles,
        final Map<String, String> serverProvidedEnvironment, final Map<String, String> extraEnvironment)
        throws SetUpJobException {
    final Path genieDirectory = PathUtils.jobGenieDirectoryPath(jobDirectory);
    final Path envScriptPath = PathUtils.composePath(genieDirectory,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_RESOURCE);
    final Path envScriptLogPath = PathUtils.composePath(genieDirectory, JobConstants.LOGS_PATH_VAR,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_LOG_FILE_NAME);
    final Path envScriptOutputPath = PathUtils.composePath(genieDirectory,
            JobConstants.GENIE_AGENT_ENV_SCRIPT_OUTPUT_FILE_NAME);

    // Copy env script from resources to genie directory
    try {/*from  ww w  . jav a2  s. c  o m*/
        Files.copy(new ClassPathResource(JobConstants.GENIE_AGENT_ENV_SCRIPT_RESOURCE).getInputStream(),
                envScriptPath, StandardCopyOption.REPLACE_EXISTING);
        // Make executable
        envScriptPath.toFile().setExecutable(true, true);
    } catch (final IOException e) {
        throw new SetUpJobException("Could not copy environment script resource: ", e);
    }

    // Set up process that executes the script
    final ProcessBuilder processBuilder = new ProcessBuilder().inheritIO();

    processBuilder.environment().putAll(serverProvidedEnvironment);
    processBuilder.environment().putAll(extraEnvironment);

    final List<String> commandArgs = Lists.newArrayList(envScriptPath.toString(),
            envScriptOutputPath.toString(), envScriptLogPath.toString());

    setUpFiles.forEach(f -> commandArgs.add(f.getAbsolutePath()));

    processBuilder.command(commandArgs);

    // Run the setup script
    final int exitCode;
    try {
        exitCode = processBuilder.start().waitFor();
    } catch (final IOException e) {
        throw new SetUpJobException("Could not execute environment setup script", e);
    } catch (final InterruptedException e) {
        throw new SetUpJobException("Interrupted while waiting for environment setup script", e);
    }

    if (exitCode != 0) {
        throw new SetUpJobException("Non-zero exit code from environment setup script: " + exitCode);
    }

    // Check and return the output file
    final File envScriptOutputFile = envScriptOutputPath.toFile();

    if (!envScriptOutputFile.exists()) {
        throw new SetUpJobException("Expected output file does not exist: " + envScriptOutputPath.toString());
    }

    return envScriptOutputFile;
}

From source file:com.azurenight.maven.TroposphereMojo.java

public void runJythonScriptOnInstall(File outputDirectory, List<String> args, File outputFile)
        throws MojoExecutionException {
    getLog().info("running " + args + " in " + outputDirectory);
    ProcessBuilder pb = new ProcessBuilder(args);
    pb.directory(outputDirectory);//from w  ww.  j  a v  a 2  s . co  m
    pb.environment().put("BASEDIR", project.getBasedir().getAbsolutePath());
    final Process p;
    ByteArrayOutputStream stdoutBaos = null;
    ByteArrayOutputStream stderrBaos = null;
    try {
        p = pb.start();
    } catch (IOException e) {
        throw new MojoExecutionException("Executing jython failed. tried to run: " + pb.command(), e);
    }
    if (outputFile == null) {
        stdoutBaos = new ByteArrayOutputStream();
        copyIO(p.getInputStream(), stdoutBaos);
    } else {
        try {
            copyIO(p.getInputStream(), new FileOutputStream(outputFile));
        } catch (FileNotFoundException e) {
            throw new MojoExecutionException("Failed to copy output to : " + outputFile.getAbsolutePath(), e);
        }
    }
    stderrBaos = new ByteArrayOutputStream();
    copyIO(p.getErrorStream(), stderrBaos);
    copyIO(System.in, p.getOutputStream());
    try {
        boolean error = false;
        if (p.waitFor() != 0) {
            error = true;
        }
        if (getLog().isDebugEnabled() && stdoutBaos != null) {
            getLog().debug(stdoutBaos.toString());
        }
        if (getLog().isErrorEnabled() && stderrBaos != null) {
            getLog().error(stderrBaos.toString());
        }
        if (error) {
            throw new MojoExecutionException("Jython failed with return code: " + p.exitValue());
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Python tests were interrupted", e);
    }

}

From source file:org.jenkinsci.plugins.workflow.support.steps.ExecutorStepTest.java

private void startJnlpProc() throws Exception {
    killJnlpProc();//from  www.  j av  a  2s .c  o  m
    ProcessBuilder pb = new ProcessBuilder(JavaEnvUtils.getJreExecutable("java"), "-jar",
            Which.jarFile(Launcher.class).getAbsolutePath(), "-jnlpUrl",
            story.j.getURL() + "computer/dumbo/slave-agent.jnlp");
    try {
        ProcessBuilder.class.getMethod("inheritIO").invoke(pb);
    } catch (NoSuchMethodException x) {
        // prior to Java 7
    }
    System.err.println("Running: " + pb.command());
    jnlpProc = pb.start();
}