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:nz.co.fortytwo.signalk.handler.GitHandler.java

private void runNpmInstall(final File output, File destDir) throws Exception {
    FileUtils.writeStringToFile(output, "\nBeginning npm install", true);
    ProcessBuilder pb = new ProcessBuilder("npm", "install");
    Map<String, String> env = System.getenv();
    if (env.containsKey("PATH")) {
        pb.environment().put("PATH", env.get("PATH"));
    }//from   w  w w . j  a  v a  2 s.c  o  m
    if (env.containsKey("Path")) {
        pb.environment().put("Path", env.get("Path"));
    }
    if (env.containsKey("path")) {
        pb.environment().put("path", env.get("path"));
    }
    pb.directory(destDir);
    pb.redirectErrorStream(true);
    pb.redirectOutput(output);
    final Process p = pb.start();
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                p.waitFor();
                FileUtils.writeStringToFile(output, "\nDONE: Npm ended sucessfully", true);
            } catch (Exception e) {
                try {
                    logger.error(e);
                    FileUtils.writeStringToFile(output, "\nNpm ended badly:" + e.getMessage(), true);
                    FileUtils.writeStringToFile(output, "\n" + e.getStackTrace(), true);
                } catch (IOException e1) {
                    logger.error(e1);
                }
            }
        }

    };
    t.start();
}

From source file:org.lantern.CommandLine.java

private void createProcess() {
    try {/*from  www  .  j a v  a  2s.  co  m*/
        ProcessBuilder builder = new ProcessBuilder(commandAndArgs);
        builder.redirectErrorStream(true);
        builder.environment().putAll(env);

        proc = builder.start();
        executed = true;
    } catch (IOException e) {
        throw new WebDriverException(e);
    }
}

From source file:org.apache.geode.test.junit.rules.gfsh.GfshRule.java

protected ProcessBuilder toProcessBuilder(GfshScript gfshScript, Path gfshPath, File workingDir) {
    List<String> commandsToExecute = new ArrayList<>();
    commandsToExecute.add(gfshPath.toAbsolutePath().toString());

    for (String command : gfshScript.getCommands()) {
        commandsToExecute.add("-e " + command);
    }//from   www .  j a  v a2 s  . c o  m

    ProcessBuilder processBuilder = new ProcessBuilder(commandsToExecute);
    processBuilder.directory(workingDir);

    List<String> extendedClasspath = gfshScript.getExtendedClasspath();
    if (!extendedClasspath.isEmpty()) {
        Map<String, String> environmentMap = processBuilder.environment();
        String classpathKey = "CLASSPATH";
        String existingJavaArgs = environmentMap.get(classpathKey);
        String specified = String.join(PATH_SEPARATOR, extendedClasspath);
        String newValue = String.format("%s%s", existingJavaArgs == null ? "" : existingJavaArgs + ":",
                specified);
        environmentMap.put(classpathKey, newValue);
    }

    return processBuilder;
}

From source file:org.apache.hadoop.ha.ShellCommandFencer.java

@Override
public boolean tryFence(HAServiceTarget target, String cmd) {
    ProcessBuilder builder;

    if (!Shell.WINDOWS) {
        builder = new ProcessBuilder("bash", "-e", "-c", cmd);
    } else {// ww w  . j  a  v a2  s  .  c  o m
        builder = new ProcessBuilder("cmd.exe", "/c", cmd);
    }

    setConfAsEnvVars(builder.environment());
    addTargetInfoAsEnvVars(target, builder.environment());

    Process p;
    try {
        p = builder.start();
        p.getOutputStream().close();
    } catch (IOException e) {
        LOG.warn("Unable to execute " + cmd, e);
        return false;
    }

    String pid = tryGetPid(p);
    LOG.info("Launched fencing command '" + cmd + "' with " + ((pid != null) ? ("pid " + pid) : "unknown pid"));

    String logPrefix = abbreviate(cmd, ABBREV_LENGTH);
    if (pid != null) {
        logPrefix = "[PID " + pid + "] " + logPrefix;
    }

    // Pump logs to stderr
    StreamPumper errPumper = new StreamPumper(LOG, logPrefix, p.getErrorStream(),
            StreamPumper.StreamType.STDERR);
    errPumper.start();

    StreamPumper outPumper = new StreamPumper(LOG, logPrefix, p.getInputStream(),
            StreamPumper.StreamType.STDOUT);
    outPumper.start();

    int rc;
    try {
        rc = p.waitFor();
        errPumper.join();
        outPumper.join();
    } catch (InterruptedException ie) {
        LOG.warn("Interrupted while waiting for fencing command: " + cmd);
        return false;
    }

    return rc == 0;
}

From source file:de.jcup.egradle.core.process.SimpleProcessExecutor.java

@Override
public int execute(ProcessConfiguration wdProvider, EnvironmentProvider envProvider,
        ProcessContext processContext, String... commands) throws IOException {
    notNull(wdProvider, "'wdProvider' may not be null");
    notNull(envProvider, "'envProvider' may not be null");
    String wd = wdProvider.getWorkingDirectory();
    /* Working directory */
    File workingDirectory = null;
    if (StringUtils.isNotBlank(wd)) {
        workingDirectory = new File(wd);
    }/*from  w ww . j a va  2 s  .  c  o m*/
    if (workingDirectory != null) {
        if (!workingDirectory.exists()) {
            throw new FileNotFoundException("Working directory does not exist:" + workingDirectory);
        }
    }
    /* Create process with dedicated environment */
    ProcessBuilder pb = new ProcessBuilder(commands);
    Map<String, String> env = envProvider.getEnvironment();
    /* init environment */
    if (env != null) {
        Map<String, String> pbEnv = pb.environment();
        for (String key : env.keySet()) {
            pbEnv.put(key, env.get(key));
        }
    }
    /* init working directory */
    pb.directory(workingDirectory);
    pb.redirectErrorStream(true);

    Date started = new Date();
    Process p = startProcess(pb);
    ProcessTimeoutTerminator timeoutTerminator = null;
    if (timeOutInSeconds != ENDLESS_RUNNING) {
        timeoutTerminator = new ProcessTimeoutTerminator(p, outputHandler, timeOutInSeconds);
        timeoutTerminator.start();
    }
    ProcessCancelTerminator cancelTerminator = new ProcessCancelTerminator(p,
            processContext.getCancelStateProvider());
    Thread cancelCheckThread = new Thread(cancelTerminator, "process-cancel-terminator");
    cancelCheckThread.start();

    handleProcessStarted(envProvider, p, started, workingDirectory, commands);

    handleOutputStreams(p, timeoutTerminator, processContext.getCancelStateProvider());

    /* wait for execution */
    try {
        while (isAlive(p)) {
            waitFor(p);
        }
    } catch (InterruptedException e) {
        /* ignore */
    }
    /* done */
    int exitValue = p.exitValue();
    handleProcessEnd(p);
    return exitValue;
}

From source file:com.blackducksoftware.integration.hub.cli.SimpleScanService.java

/**
 * If running in an environment that handles process creation, this method should be overridden to construct a
 * process to execute the scan in the environment-specific way.
 *//*  w w  w.jav  a 2  s.c om*/
public Result executeScan(HubServerConfig hubServerConfig, HubSupportHelper hubSupportHelper,
        CIEnvironmentVariables ciEnvironmentVariables, CLILocation cliLocation, int scanMemory,
        boolean verboseRun, boolean dryRun, String project, String version, List<String> scanTargetPaths,
        String workingDirectoryPath, List<String> cmd)
        throws IOException, InterruptedException, IllegalArgumentException, EncryptionException {
    printCommand(cmd);

    final File standardOutFile = new File(logDirectory, "CLI_Output.txt");
    standardOutFile.createNewFile();
    try (FileOutputStream outputFileStream = new FileOutputStream(standardOutFile)) {
        ScannerSplitStream splitOutputStream = new ScannerSplitStream(logger, outputFileStream);
        final ProcessBuilder processBuilder = new ProcessBuilder(cmd).redirectError(PIPE).redirectOutput(PIPE);

        processBuilder.environment().put("BD_HUB_PASSWORD",
                hubServerConfig.getGlobalCredentials().getDecryptedPassword());

        final String bdioEnvVar = ciEnvironmentVariables.getValue("BD_HUB_DECLARED_COMPONENTS");
        if (StringUtils.isNotBlank(bdioEnvVar)) {
            processBuilder.environment().put("BD_HUB_DECLARED_COMPONENTS", bdioEnvVar);
        }

        Process hubCliProcess = processBuilder.start();

        // The cli logs go the error stream for some reason
        StreamRedirectThread redirectThread = new StreamRedirectThread(hubCliProcess.getErrorStream(),
                splitOutputStream);
        redirectThread.start();

        int returnCode = hubCliProcess.waitFor();

        // the join method on the redirect thread will wait until the thread is dead
        // the thread will die when it reaches the end of stream and the run method is finished
        redirectThread.join();

        splitOutputStream.flush();
        logger.info(IoUtils.toString((hubCliProcess.getInputStream())));

        logger.info("Hub CLI return code : " + returnCode);
        logger.info("You can view the BlackDuck Scan CLI logs at : '" + logDirectory.getCanonicalPath() + "'");

        if (returnCode == 0) {
            return Result.SUCCESS;
        } else {
            return Result.FAILURE;
        }
    }
}

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  va  2 s . c  om
        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.streamsets.pipeline.stage.executor.shell.ShellExecutor.java

private void executeScript(Record record) throws StageException {
    File script = null;/* w  w w. j  a  v  a 2s.  c  o  m*/
    try {
        script = File.createTempFile("sdc-script-executor", ".sh");
        ELVars variables = getContext().createELVars();
        RecordEL.setRecordInContext(variables, record);

        // Serialize the script into a file on disk (in temporary location)
        FileUtils.writeStringToFile(script, config.script);

        ImmutableList.Builder<String> commandBuilder = new ImmutableList.Builder<>();
        if (impersonationMode != ImpersonationMode.DISABLED) {
            commandBuilder.add(sudo);
            commandBuilder.add("-E");
            commandBuilder.add("-u");
            commandBuilder.add(user);
        }

        commandBuilder.add(shell);
        commandBuilder.add(script.getPath());

        List<String> commandLine = commandBuilder.build();

        // External process configuration
        ProcessBuilder processBuilder = new ProcessBuilder(commandLine);
        for (Map.Entry<String, String> entry : config.environmentVariables.entrySet()) {
            processBuilder.environment().put(eval.eval(variables, entry.getKey(), String.class),
                    eval.eval(variables, entry.getValue(), String.class));
        }

        // Start process and configure forwarders for stderr/stdin
        LOG.debug("Executing script: {}", StringUtils.join(commandLine, " "));
        Process process = processBuilder.start();
        new Thread(new ProcessStdIOForwarder(false, process.getInputStream())).start();
        new Thread(new ProcessStdIOForwarder(true, process.getErrorStream())).start();

        int pid = retrievePidIfFeasible(process);
        LOG.debug("Created process with PID {}", pid);

        // User configures the maximal time for the script execution
        boolean finished = process.waitFor(timeout, TimeUnit.MILLISECONDS);
        if (!finished) {
            process.destroyForcibly();
            throw new OnRecordErrorException(record, Errors.SHELL_002);
        }

        if (process.exitValue() != 0) {
            throw new OnRecordErrorException(record, Errors.SHELL_003, process.exitValue());
        }
    } catch (OnRecordErrorException e) {
        errorRecordHandler.onError(e);
    } catch (Exception e) {
        errorRecordHandler.onError(new OnRecordErrorException(record, Errors.SHELL_001, e.toString(), e));
    } finally {
        if (script != null && script.exists()) {
            script.delete();
        }
    }
}

From source file:org.apache.beam.runners.apex.ApexYarnLauncher.java

protected AppHandle launchApp(LaunchParams params) throws IOException {
    File tmpFile = File.createTempFile("beam-runner-apex", "params");
    tmpFile.deleteOnExit();//  w  w w  .  j av a  2  s. com
    try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
        SerializationUtils.serialize(params, fos);
    }
    if (params.getCmd() == null) {
        ApexYarnLauncher.main(new String[] { tmpFile.getAbsolutePath() });
    } else {
        String cmd = params.getCmd() + " " + tmpFile.getAbsolutePath();
        ByteArrayOutputStream consoleOutput = new ByteArrayOutputStream();
        LOG.info("Executing: {} with {}", cmd, params.getEnv());

        ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd);
        Map<String, String> env = pb.environment();
        env.putAll(params.getEnv());
        Process p = pb.start();
        ProcessWatcher pw = new ProcessWatcher(p);
        InputStream output = p.getInputStream();
        InputStream error = p.getErrorStream();
        while (!pw.isFinished()) {
            IOUtils.copy(output, consoleOutput);
            IOUtils.copy(error, consoleOutput);
        }
        if (pw.rc != 0) {
            String msg = "The Beam Apex runner in non-embedded mode requires the Hadoop client"
                    + " to be installed on the machine from which you launch the job"
                    + " and the 'hadoop' script in $PATH";
            LOG.error(msg);
            throw new RuntimeException(
                    "Failed to run: " + cmd + " (exit code " + pw.rc + ")" + "\n" + consoleOutput.toString());
        }
    }
    return new AppHandle() {
        @Override
        public boolean isFinished() {
            // TODO (future PR): interaction with child process
            LOG.warn("YARN application runs asynchronously and status check not implemented.");
            return true;
        }

        @Override
        public void shutdown(ShutdownMode arg0) throws LauncherException {
            // TODO (future PR): interaction with child process
            throw new UnsupportedOperationException();
        }
    };
}

From source file:com.alibaba.jstorm.utils.JStormUtils.java

protected static Process launchProcess(final String[] cmdlist, final Map<String, String> environment)
        throws IOException {
    ArrayList<String> buff = new ArrayList<String>();
    for (String tok : cmdlist) {
        if (!tok.isEmpty()) {
            buff.add(tok);//from   ww w  .j  a  va  2s .  c o  m
        }
    }

    ProcessBuilder builder = new ProcessBuilder(buff);
    builder.redirectErrorStream(true);
    Map<String, String> process_evn = builder.environment();
    for (Entry<String, String> entry : environment.entrySet()) {
        process_evn.put(entry.getKey(), entry.getValue());
    }

    return builder.start();
}