Example usage for java.lang ProcessBuilder environment

List of usage examples for java.lang ProcessBuilder environment

Introduction

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

Prototype

Map environment

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

Click Source Link

Usage

From source file:org.eclipse.gyrex.jobs.internal.externalprocess.ExternalProcessJob.java

private void setEnvironmentVariable(final ProcessBuilder builder, final String key, final String value) {
    log.debug("Setting environment variable: {} = {}", key, value);
    builder.environment().put(key, value);
}

From source file:org.dbflute.maven.plugin.command.CommandExecutor.java

public void execute(String cmd) throws MojoExecutionException, MojoFailureException {
    File dbfluteClientDir = plugin.getDbfluteClientDir();
    if (!dbfluteClientDir.isDirectory()) {
        LogUtil.getLog()//from   www. j  av a2s  .  c om
                .info("Create dbflute client directory. " + "Try to run \'mvn dbflute:create-client\'.");
        return;
    }

    List<String> cmds = new ArrayList<String>();
    if (SystemUtil.isWindows()) {
        cmds.add("cmd.exe");
        cmds.add("/c");
        cmds.add(cmd + ".bat");
        environment.put("pause_at_end", "n");
    } else {
        cmds.add("/bin/bash");
        cmds.add(cmd + ".sh");
    }
    // TODO Mac?

    plugin.updateArgs(cmds);

    LogUtil.getLog().info("Running " + StringUtils.join(cmds.toArray(), " "));
    ProcessBuilder builder = new ProcessBuilder(cmds);
    if (environment.size() > 0) {
        builder.environment().putAll(environment);
    }
    Process process;
    try {
        process = builder.directory(dbfluteClientDir).redirectErrorStream(true).start();
    } catch (IOException e) {
        throw new MojoExecutionException("Could not run the command.", e);
    }

    try (InputStream stdin = process.getInputStream(); OutputStream stdout = process.getOutputStream()) {
        InputStreamThread ist = new InputStreamThread(stdin);
        OutputStreamThread ost = new OutputStreamThread(System.in, stdout);
        ist.start();
        ost.start();

        int exitValue = process.waitFor();

        ist.join();
        //ost.join();

        if (exitValue != 0) {
            throw new MojoFailureException("Build Failed. The exit value is " + exitValue + ".");
        }
    } catch (InterruptedException e) {
        throw new MojoExecutionException("Could not wait a process.", e);
    } catch (IOException e) {
        throw new MojoExecutionException("I/O error.", e);
    }
}

From source file:fitnesse.testsystems.CommandRunner.java

public void asynchronousStart() throws IOException {
    ProcessBuilder processBuilder = new ProcessBuilder(command);
    processBuilder.environment().putAll(determineEnvironment());
    if (LOG.isLoggable(Level.FINE)) {
        LOG.fine("Starting process " + asList(command));
    }//from   ww  w. j  a va  2 s  .  c o m
    process = processBuilder.start();

    sendCommandStartedEvent();
    redirectOutputs(process, executionLogListener);
}

From source file:org.sonar.process.monitor.JavaProcessLauncher.java

private ProcessBuilder create(JavaCommand javaCommand) {
    List<String> commands = new ArrayList<>();
    commands.add(buildJavaPath());// w w  w. j a va  2s.c  om
    commands.addAll(javaCommand.getJavaOptions());
    // TODO warning - does it work if temp dir contains a whitespace ?
    commands.add(String.format("-Djava.io.tmpdir=%s", tempDir.getAbsolutePath()));
    commands.add(getJmxAgentCommand());
    commands.addAll(buildClasspath(javaCommand));
    commands.add(javaCommand.getClassName());
    commands.add(buildPropertiesFile(javaCommand).getAbsolutePath());

    ProcessBuilder processBuilder = new ProcessBuilder();
    processBuilder.command(commands);
    processBuilder.directory(javaCommand.getWorkDir());
    processBuilder.environment().putAll(javaCommand.getEnvVariables());
    processBuilder.redirectErrorStream(true);
    return processBuilder;
}

From source file:com.blackducksoftware.integration.hub.detect.util.executable.Executable.java

public ProcessBuilder createProcessBuilder() {
    final List<String> processBuilderArguments = createProcessBuilderArguments();
    final ProcessBuilder processBuilder = new ProcessBuilder(processBuilderArguments);
    processBuilder.directory(workingDirectory);
    final Map<String, String> processBuilderEnvironment = processBuilder.environment();
    final Map<String, String> systemEnv = System.getenv();
    for (final String key : systemEnv.keySet()) {
        populateEnvironmentMap(processBuilderEnvironment, key, systemEnv.get(key));
    }//  www  .  jav a  2s.  c o  m
    for (final String key : environmentVariables.keySet()) {
        populateEnvironmentMap(processBuilderEnvironment, key, environmentVariables.get(key));
    }
    return processBuilder;
}

From source file:de.uni_potsdam.hpi.asg.common.io.Invoker.java

private ProcessReturn invoke(String[] cmd, List<String> params, File folder, int timeout) {
    List<String> command = new ArrayList<String>();
    command.addAll(Arrays.asList(cmd));
    command.addAll(params);//from www  .j  a  v a 2  s.  c om
    ProcessReturn retVal = new ProcessReturn(Arrays.asList(cmd), params);
    Process process = null;
    try {
        logger.debug("Exec command: " + command.toString());
        //System.out.println(timeout + ": " + command.toString());
        ProcessBuilder builder = new ProcessBuilder(command);
        builder.directory(folder);
        builder.environment(); // bugfix setting env in test-mode (why this works? i dont know..)
        process = builder.start();

        Thread timeoutThread = null;
        if (timeout > 0) {
            timeoutThread = new Thread(new Timeout(Thread.currentThread(), timeout));
            timeoutThread.setName("Timout for " + command.toString());
            timeoutThread.start();
        }
        IOStreamReader ioreader = new IOStreamReader(process);
        Thread streamThread = new Thread(ioreader);
        streamThread.setName("StreamReader for " + command.toString());
        streamThread.start();
        process.waitFor();
        streamThread.join();
        if (timeoutThread != null) {
            timeoutThread.interrupt();
        }
        String out = ioreader.getResult();
        //System.out.println(out);
        if (out == null) {
            //System.out.println("out = null");
            retVal.setStatus(Status.noio);
        }
        retVal.setCode(process.exitValue());
        retVal.setStream(out);
        retVal.setStatus(Status.ok);
    } catch (InterruptedException e) {
        process.destroy();
        retVal.setTimeout(timeout);
        retVal.setStatus(Status.timeout);
    } catch (IOException e) {
        logger.error(e.getLocalizedMessage());
        retVal.setStatus(Status.ioexception);
    }
    return retVal;
}

From source file:org.geoserver.ogr.core.AbstractToolWrapper.java

/**
 * Runs the specified command appending the output to the string builder and
 * returning the exit code.//from   ww w  .  j  ava2s. c  om
 * 
 * @param cmd the command to run and its arguments
 * @param sb command output is appended here
 * @return the exit code of the invoked command. Usually, 0 indicates normal termination
 * @throws IOException
 * @throws InterruptedException
 */
protected int run(List<String> cmd, StringBuilder sb) throws IOException, InterruptedException {
    // run the process and grab the output for error reporting purposes
    ProcessBuilder builder = new ProcessBuilder(cmd);
    if (environment != null)
        builder.environment().putAll(environment);
    builder.redirectErrorStream(true);
    Process p = builder.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line = null;
    while ((line = reader.readLine()) != null) {
        if (sb != null) {
            sb.append("\n");
            sb.append(line);
        }
    }
    return p.waitFor();
}

From source file:repast.simphony.data.analysis.AnalysisPluginRunner.java

public void run(AnalysisPluginWizard wizard) {
    String[] command = null;//from w w  w  .ja va  2 s. c  o m
    try {
        command = wizard.getExecutionCommand();
        Map<String, String> envVars = wizard.getEnvVars();

        if (command == null) {

            String message = wizard.getCannotRunMessage();
            if (message != null) {
                JOptionPane.showMessageDialog(null, message);
            }

        } else {

            Process process;

            for (String s : command)
                System.out.print(s + " ");
            System.out.print("\n");

            ProcessBuilder builder = new ProcessBuilder(command).redirectErrorStream(true);
            System.out.println(envVars);
            builder.environment().putAll(envVars);
            System.out.println(builder.directory(new File(".").getAbsoluteFile()));
            System.out.println(builder.directory());
            process = builder.start();

            PluginOutputStream pos = new PluginOutputStream(process.getInputStream());
            pos.start();

            PluginOutputStream pos2 = new PluginOutputStream(process.getErrorStream());
            pos2.start();

        }

    } catch (Exception e) {

        e.printStackTrace();

        // LOG.error("Wizard.run: Error executing " + name
        // + ".  Command is: '" + arrayToString(command) + "'",
        // e);
    }
}

From source file:com.netscape.cms.profile.constraint.ExternalProcessConstraint.java

public void validate(IRequest request, X509CertInfo info) throws ERejectException {
    CMS.debug("About to execute command: " + this.executable);
    ProcessBuilder pb = new ProcessBuilder(this.executable);

    // set up process environment
    Map<String, String> env = pb.environment();
    for (String k : envVars.keySet()) {
        String v = request.getExtDataInString(envVars.get(k));
        if (v != null)
            env.put(k, v);//from   w w  w.  j  av  a  2s.c  o m
    }
    for (String k : extraEnvVars.keySet()) {
        String v = request.getExtDataInString(extraEnvVars.get(k));
        if (v != null)
            env.put(k, v);
    }

    Process p;
    String stdout = "";
    String stderr = "";
    boolean timedOut;
    try {
        p = pb.start();
        timedOut = !p.waitFor(timeout, TimeUnit.SECONDS);
        if (timedOut)
            p.destroyForcibly();
        else
            stdout = IOUtils.toString(p.getInputStream());
        stderr = IOUtils.toString(p.getErrorStream());
    } catch (Throwable e) {
        String msg = "Caught exception while executing command: " + this.executable;
        CMS.debug(msg);
        CMS.debug(e);
        throw new ERejectException(msg, e);
    }
    if (timedOut)
        throw new ERejectException("Request validation timed out");
    int exitValue = p.exitValue();
    CMS.debug("ExternalProcessConstraint: exit value: " + exitValue);
    CMS.debug("ExternalProcessConstraint: stdout: " + stdout);
    CMS.debug("ExternalProcessConstraint: stderr: " + stderr);
    if (exitValue != 0)
        throw new ERejectException(stdout);
}

From source file:org.eclipse.che.plugin.testing.phpunit.server.PHPUnitTestEngine.java

public ProcessHandler executeTests(TestExecutionContext context) {
    String projectPath = context.getProjectPath();
    String testTargetRelativePath = context.getFilePath();
    String projectAbsolutePath = ResourcesPlugin.getPathToWorkspace() + projectPath;
    File testTargetFile = getTestTargetFile(testTargetRelativePath, projectAbsolutePath);
    File testTargetWorkingDirectory = testTargetFile.isDirectory() ? testTargetFile
            : testTargetFile.getParentFile();
    // Get appropriate path to executable
    String phpUnitExecutable = PHPUNIT_GLOBAL;
    if (hasComposerRunner(projectPath)) {
        phpUnitExecutable = projectAbsolutePath + PHPUNIT_COMPOSER;
    }/*w  ww.ja  va2 s  .  c om*/
    // Get appropriate logger for PHP unit version
    final File printerFile = getPrinterFile();
    final String printerDirAbsolutePath = printerFile.getParentFile().getAbsolutePath();
    final CommandLine cmdRunTests = new CommandLine(phpUnitExecutable, "--include-path", printerDirAbsolutePath,
            "--printer", PRINTER_NAME, getTestTarget(testTargetFile));
    ProcessBuilder pb = new ProcessBuilder().redirectErrorStream(true).directory(testTargetWorkingDirectory)
            .command(cmdRunTests.toShellCommand());
    pb.environment().put("ZEND_PHPUNIT_PORT", String.valueOf(PRINTER_PORT));
    try {
        return new ProcessHandler(pb.start());
    } catch (IOException e) {
        LOG.error("Can't run PHPUnit", e);
    }

    return null;
}