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:com.teradata.benchto.driver.macro.shell.ShellMacroExecutionDriver.java

public void runBenchmarkMacro(String macroName, Map<String, String> environment) {
    try {//  w ww .j av a  2 s.  c  o m
        String macroCommand = getMacroCommand(macroName);
        ProcessBuilder processBuilder = new ProcessBuilder(SHELL, "-c", macroCommand);
        processBuilder.environment().putAll(environment);
        Process macroProcess = processBuilder.start();
        LOGGER.info("Executing macro: '{}'", macroCommand);
        macroProcess.waitFor();
        boolean completedSuccessfully = macroProcess.exitValue() == 0;
        printOutput(macroProcess, !completedSuccessfully);
        checkState(completedSuccessfully, "Macro %s exited with code %s", macroName, macroProcess.exitValue());
    } catch (IOException | InterruptedException e) {
        throw new BenchmarkExecutionException("Could not execute macro " + macroName, e);
    }
}

From source file:org.apache.jackrabbit.webdav.simple.LitmusTest.java

private void assertLitmus(ProcessBuilder builder, String tests, int exit) throws Exception {
    builder.environment().put("TESTS", tests);
    Process process = builder.start();
    IOUtils.copy(process.getInputStream(), System.out);
    assertEquals(exit, process.waitFor());
}

From source file:org.wso2.msf4j.ballerina.BallerinaService.java

@POST
@Consumes(MediaType.APPLICATION_JSON)//w  w w.jav  a 2  s  .co m
@Produces(MediaType.TEXT_PLAIN)
@Path("/executeAsProcess")
public Response executeBallerinaWithArgsAsProcess(BallerinaContent ballerinaContent) {
    UUID requestId = UUID.randomUUID();
    log.info(requestId.toString() + " <<< " + new Gson().toJson(ballerinaContent));
    String result;
    try {
        java.nio.file.Path path = Paths.get(Application.ballerinaTmp.toString(), requestId.toString() + ".bal");
        Files.write(path, ballerinaContent.getContent().getBytes());
        fileCleaningTracker.track(path.toFile(), ballerinaContent);
        List<String> processArgs = new ArrayList<>();
        processArgs.add(Application.ballerinaPath.toString());
        processArgs.add("run");
        processArgs.add(path.toString());
        processArgs.addAll(Arrays.asList(ballerinaContent.getArguments().split(";")));
        ProcessBuilder processBuilder = new ProcessBuilder(processArgs);
        processBuilder.environment().put("JAVA_HOME", System.getProperty("java.home"));
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();

        if (!process.waitFor(8, TimeUnit.SECONDS)) {
            // Run the psfinder script which will get the pid of started ballerina process and kill that.
            Process exec = Runtime.getRuntime().exec(
                    new String[] { Application.psFinder.toFile().getAbsolutePath(), requestId.toString() });
            exec.waitFor();
            process.destroyForcibly();
            result = "Process took too long\nSystem will exit";
        } else {
            result = IOUtils.toString(process.getInputStream());
        }
    } catch (Exception e) {
        result = "Something went wrong. Try again";
        log.error(e);
    }
    log.info(requestId.toString() + " >>> " + result);
    return Response.ok().entity(result).header("Access-Control-Allow-Origin", "*").build();
}

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

protected static Process launchProcess(final List<String> cmdlist, final Map<String, String> environment)
        throws IOException {
    ProcessBuilder builder = new ProcessBuilder(cmdlist);
    builder.redirectErrorStream(true);/* ww  w  . ja  v  a  2 s  .co  m*/
    Map<String, String> process_evn = builder.environment();
    for (Entry<String, String> entry : environment.entrySet()) {
        process_evn.put(entry.getKey(), entry.getValue());
    }

    return builder.start();
}

From source file:io.jmnarloch.cd.go.plugin.sbt.SbtTaskExecutor.java

/**
 * Builds the SBT process to be executed
 *
 * @param environment the build environment
 * @param config      the build configuration
 * @return the SBT process//from ww  w .  ja v  a 2 s .  co m
 */
private ProcessBuilder buildSbtProcess(ExecutionContext environment, ExecutionConfiguration config) {

    final Map<String, String> env = environment.getEnvironmentVariables();

    final List<String> command = parse(config, env);

    logger.debug("Executing command: " + command);

    final ProcessBuilder builder = new ProcessBuilder(command);
    builder.environment().putAll(env);
    builder.directory(new File(environment.getWorkingDirectory()));
    return builder;
}

From source file:org.apache.metron.rest.service.impl.DockerStormCLIWrapper.java

@Override
protected ProcessBuilder getProcessBuilder(final String... command) {
    final String[] dockerCommand = { "docker-compose", "-f", environment.getProperty("docker.compose.path"),
            "-p", "metron", "exec", "storm" };
    final ProcessBuilder pb = new ProcessBuilder(ArrayUtils.addAll(dockerCommand, command));
    final Map<String, String> pbEnvironment = pb.environment();
    pbEnvironment.put("METRON_VERSION", environment.getProperty("metron.version"));
    setDockerEnvironment(pbEnvironment);
    return pb;//from  w w w.  j  a v  a2  s  .  c  o  m
}

From source file:org.apache.hive.hcatalog.templeton.tool.TrivialExecService.java

public Process run(List<String> cmd, List<String> removeEnv, Map<String, String> environmentVariables)
        throws IOException {
    LOG.info("run(cmd, removeEnv, environmentVariables)");
    LOG.info("Starting cmd: " + cmd);
    ProcessBuilder pb = new ProcessBuilder(cmd);
    for (String key : removeEnv) {
        if (pb.environment().containsKey(key)) {
            LOG.info("Removing env var: " + key + "=" + pb.environment().get(key));
        }/*from  w  ww .ja v a 2s.co  m*/
        pb.environment().remove(key);
    }
    pb.environment().putAll(environmentVariables);
    logDebugInfo("========Starting process with env:========", pb.environment());
    printContentsOfDir(".");
    return pb.start();
}

From source file:org.apache.asterix.test.aql.TestExecutor.java

private static String executeVagrantManagix(ProcessBuilder pb, String command) throws Exception {
    pb.command("vagrant", "ssh", "cc", "--", pb.environment().get("MANAGIX_HOME") + command);
    Process p = pb.start();//  w  ww  .j  ava2  s . c o  m
    p.waitFor();
    InputStream input = p.getInputStream();
    return IOUtils.toString(input, StandardCharsets.UTF_8.name());
}

From source file:org.apache.asterix.event.management.EventExecutor.java

public void executeEvent(Node node, String script, List<String> args, boolean isDaemon, Cluster cluster,
        Pattern pattern, IOutputHandler outputHandler, AsterixEventServiceClient client) throws IOException {
    List<String> pargs = new ArrayList<>();
    pargs.add("/bin/bash");
    pargs.add(client.getEventsHomeDir() + File.separator + AsterixEventServiceUtil.EVENT_DIR + File.separator
            + EXECUTE_SCRIPT);/* w w  w  . j av a2  s  . c o  m*/
    StringBuilder envBuffer = new StringBuilder(IP_LOCATION + "=" + node.getClusterIp() + " ");
    boolean isMasterNode = node.getId().equals(cluster.getMasterNode().getId());

    if (!node.getId().equals(EventDriver.CLIENT_NODE_ID) && cluster.getEnv() != null) {
        for (Property p : cluster.getEnv().getProperty()) {
            if (p.getKey().equals("JAVA_HOME")) {
                String val = node.getJavaHome() == null ? p.getValue() : node.getJavaHome();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else if (p.getKey().equals(EventUtil.NC_JAVA_OPTS)) {
                if (!isMasterNode) {
                    appendJavaOpts(node, envBuffer, p);
                }
            } else if (p.getKey().equals(EventUtil.CC_JAVA_OPTS)) {
                if (isMasterNode) {
                    appendJavaOpts(node, envBuffer, p);
                }
            } else if (p.getKey().equals("LOG_DIR")) {
                String val = node.getLogDir() == null ? p.getValue() : node.getLogDir();
                envBuffer.append(p.getKey() + "=" + val + " ");
            } else {
                envBuffer.append(p.getKey() + "=" + p.getValue() + " ");
            }

        }
        pargs.add(cluster.getUsername() == null ? System.getProperty("user.name") : cluster.getUsername());
    }

    StringBuilder argBuffer = new StringBuilder();
    if (args != null && args.size() > 0) {
        for (String arg : args) {
            argBuffer.append(arg + " ");
        }
    }

    ProcessBuilder pb = new ProcessBuilder(pargs);
    pb.environment().put(IP_LOCATION, node.getClusterIp());
    pb.environment().put(CLUSTER_ENV, envBuffer.toString());
    pb.environment().put(SCRIPT, script);
    pb.environment().put(ARGS, argBuffer.toString());
    pb.environment().put(DAEMON, Boolean.toString(isDaemon));
    Process p = pb.start();
    if (!isDaemon) {
        BufferedInputStream bis = new BufferedInputStream(p.getInputStream());
        StringWriter writer = new StringWriter();
        IOUtils.copy(bis, writer, "UTF-8");
        String result = writer.getBuffer().toString();
        OutputAnalysis analysis = outputHandler.reportEventOutput(pattern.getEvent(), result);
        if (!analysis.isExpected()) {
            throw new IOException(analysis.getErrorMessage() + result);
        }
    }
}

From source file:net.urlgrey.mythpodcaster.transcode.SegmentedVodTranscoderImpl.java

public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile,
        File outputFile) throws Exception {
    LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile ["
            + outputFile.getAbsolutePath() + "]");

    SegmenterTranscoderConfigurationItem config = (SegmenterTranscoderConfigurationItem) genericConfig;
    List<String> commandList = new ArrayList<String>();
    commandList.add(niceLocation);//from w ww . j a  v  a2 s  .  c o m
    commandList.add("-n");
    commandList.add(Integer.toString(config.getNiceness()));
    commandList.add(segmenterLocation);
    commandList.add(inputFile.getAbsolutePath());
    commandList.add(config.getSegmentDuration());
    commandList.add(config.getSegmentFilePrefix());
    commandList.add(config.getPlaylistFileName());
    commandList.add(config.getHttpPrefix());
    ProcessBuilder pb = new ProcessBuilder(commandList);

    pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:");
    pb.redirectErrorStream(true);
    pb.directory(outputFile.getParentFile());
    Process process = null;

    try {
        // Get the segmenter process
        process = pb.start();
        // We give a couple of secs to complete task if needed
        Future<List<String>> stdout = pool.submit(new OutputMonitor(process.getInputStream()));
        List<String> result = stdout.get(config.getTimeout(), TimeUnit.SECONDS);
        process.waitFor();
        final int exitValue = process.exitValue();
        LOG.info("Segmenter exit value: " + exitValue);
        if (exitValue != 0) {
            for (String line : result) {
                LOG.error(line);
            }
            throw new Exception("Segmenter return code indicated failure: " + exitValue);
        }
    } catch (InterruptedException e) {
        throw new Exception("Segmenter process interrupted by another thread", e);
    } catch (ExecutionException ee) {
        throw new Exception("Something went wrong parsing Segmenter output", ee);
    } catch (TimeoutException te) {
        // We could not get the result before timeout
        throw new Exception("Segmenter process timed out", te);
    } catch (RuntimeException re) {
        // Unexpected output from Segmenter
        throw new Exception("Something went wrong parsing Segmenter output", re);
    } finally {
        if (process != null) {
            process.destroy();
        }
    }

    LOG.debug("transcoding finished");
}