List of usage examples for java.lang ProcessBuilder environment
Map environment
To view the source code for java.lang ProcessBuilder environment.
Click Source Link
From source file:com.tw.go.plugin.material.artifactrepository.yum.exec.command.ProcessRunner.java
public ProcessOutput execute(String[] command, Map<String, String> envMap) { ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = null;/* w w w .j ava 2 s . c om*/ ProcessOutput processOutput = null; try { processBuilder.environment().putAll(envMap); process = processBuilder.start(); int returnCode = process.waitFor(); List outputStream = IOUtils.readLines(process.getInputStream()); List errorStream = IOUtils.readLines(process.getErrorStream()); processOutput = new ProcessOutput(returnCode, outputStream, errorStream); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } finally { if (process != null) { closeQuietly(process.getInputStream()); closeQuietly(process.getErrorStream()); closeQuietly(process.getOutputStream()); process.destroy(); } } return processOutput; }
From source file:net.sf.mavenjython.test.PythonTestMojo.java
public void execute() throws MojoExecutionException { // all we have to do is to run nose on the source directory List<String> l = new ArrayList<String>(); if (program.equals("nose")) { l.add("nosetests.bat"); l.add("--failure-detail"); l.add("--verbose"); } else {/*from w w w.j a v a2 s.c o m*/ l.add(program); } ProcessBuilder pb = new ProcessBuilder(l); pb.directory(testOutputDirectory); pb.environment().put("JYTHONPATH", ".;" + outputDirectory.getAbsolutePath()); final Process p; getLog().info("starting python tests"); getLog().info("executing " + pb.command()); getLog().info("in directory " + testOutputDirectory); getLog().info("and also including " + outputDirectory); try { p = pb.start(); } catch (IOException e) { throw new MojoExecutionException( "Python tests execution failed. Provide the executable '" + program + "' in the path", e); } copyIO(p.getInputStream(), System.out); copyIO(p.getErrorStream(), System.err); copyIO(System.in, p.getOutputStream()); try { if (p.waitFor() != 0) { throw new MojoExecutionException("Python tests failed with return code: " + p.exitValue()); } else { getLog().info("Python tests (" + program + ") succeeded."); } } catch (InterruptedException e) { throw new MojoExecutionException("Python tests were interrupted", e); } }
From source file:es.amplia.research.maven.protodocbook.cmd.Factory.java
private void execute(File directory, String... cmd) throws Exception { ProcessBuilder pb = new ProcessBuilder(cmd); Map<String, String> env = pb.environment(); pb.directory(directory);//from w ww . j av a2 s . c om pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ((line = br.readLine()) != null) { if (this.log.isInfoEnabled()) this.log.info(line); } }
From source file:org.apache.asterix.test.aql.TestExecutor.java
private static String executeVagrantScript(ProcessBuilder pb, String node, String scriptName) throws Exception { pb.command("vagrant", "ssh", node, "--", pb.environment().get("SCRIPT_HOME") + scriptName); Process p = pb.start();//from w ww.j av a 2 s. com p.waitFor(); InputStream input = p.getInputStream(); return IOUtils.toString(input, StandardCharsets.UTF_8.name()); }
From source file:zipkin.execjar.ExecJarRule.java
@Override public Statement apply(Statement base, Description description) { return new Statement() { public void evaluate() throws Throwable { try { ProcessBuilder bootBuilder = new ProcessBuilder("java", "-jar", execJar); bootBuilder.environment().put("SERVER_PORT", String.valueOf(port())); bootBuilder.environment().putAll(environment); bootBuilder.redirectErrorStream(true); bootApp = bootBuilder.start(); CountDownLatch startedOrCrashed = new CountDownLatch(1); Thread consoleReader = new Thread(() -> { boolean foundStartMessage = false; try (BufferedReader reader = new BufferedReader( new InputStreamReader(bootApp.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { if (line.indexOf("JVM running for") != -1) { foundStartMessage = true; startedOrCrashed.countDown(); }/*from w ww . ja v a 2s.c om*/ console.add(line); } } catch (Exception e) { } finally { if (!foundStartMessage) startedOrCrashed.countDown(); } }); consoleReader.setDaemon(true); consoleReader.start(); if (!startedOrCrashed.await(10, TimeUnit.SECONDS)) { throw new AssumptionViolatedException("Took too long to start or crash"); } base.evaluate(); } finally { bootApp.destroy(); } } }; }
From source file:org.trustedanalytics.servicebroker.gearpump.service.externals.helpers.ExternalProcessExecutor.java
public ExternalProcessExecutorResult run(String[] command, String workingDir, Map<String, String> properties) { String lineToRun = Arrays.asList(command).stream().collect(Collectors.joining(" ")); LOGGER.info("==================="); LOGGER.info("Command to invoke: {}", lineToRun); ProcessBuilder processBuilder = new ProcessBuilder(command); updateEnvOfProcessBuilder(processBuilder.environment(), properties); if (workingDir != null) { processBuilder.directory(new File(workingDir)); }//from w w w . j a v a 2 s. c o m processBuilder.redirectErrorStream(true); StringBuilder processOutput = new StringBuilder(); Process process; BufferedReader stdout = null; try { process = processBuilder.start(); stdout = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = stdout.readLine()) != null) { LOGGER.debug(":::::: " + line); processOutput.append(line); processOutput.append('\n'); } try { process.waitFor(); } catch (InterruptedException e) { LOGGER.error("Command '" + lineToRun + "' interrupted.", e); } } catch (IOException e) { LOGGER.error("Problem executing external process.", e); return new ExternalProcessExecutorResult(Integer.MIN_VALUE, "", e); } finally { closeReader(stdout); } ExternalProcessExecutorResult result = new ExternalProcessExecutorResult(process.exitValue(), processOutput.toString(), null); LOGGER.info("Exit value: {}", result.getExitCode()); LOGGER.info("==================="); return result; }
From source file:com.netflix.raigad.defaultimpl.ElasticSearchProcessManager.java
public void start(boolean join_ring) throws IOException { logger.info("Starting elasticsearch server"); List<String> command = Lists.newArrayList(); if (!"root".equals(System.getProperty("user.name"))) { command.add(SUDO_STRING);/*from ww w .j ava 2 s. c om*/ command.add("-n"); command.add("-E"); } command.addAll(getStartCommand()); ProcessBuilder startEs = new ProcessBuilder(command); Map<String, String> env = startEs.environment(); env.put("DATA_DIR", config.getDataFileLocation()); startEs.directory(new File("/")); startEs.redirectErrorStream(true); Process starter = startEs.start(); logger.info("Starting Elasticsearch server ...."); try { sleeper.sleepQuietly(SCRIPT_EXECUTE_WAIT_TIME_MS); int code = starter.exitValue(); if (code == 0) logger.info("Elasticsearch server has been started"); else logger.error("Unable to start Elasticsearch server. Error code: {}", code); logProcessOutput(starter); } catch (Exception e) { logger.warn("Starting Elasticsearch has an error", e.getMessage()); } }
From source file:net.urlgrey.mythpodcaster.transcode.FFMpegTranscoderImpl.java
public void transcode(File workingDirectory, GenericTranscoderConfigurationItem genericConfig, File inputFile, File outputFile) throws Exception { LOG.info("transcode started: inputFile [" + inputFile.getAbsolutePath() + "], outputFile [" + outputFile.getAbsolutePath() + "]"); FFMpegTranscoderConfigurationItem config = (FFMpegTranscoderConfigurationItem) genericConfig; List<String> commandList = new ArrayList<String>(); commandList.add(niceLocation);//from ww w . j av a2 s . c o m commandList.add("-n"); commandList.add(Integer.toString(config.getNiceness())); commandList.add(ffmpegLocation); commandList.add("-i"); commandList.add(inputFile.getAbsolutePath()); commandList.addAll(config.getParsedEncoderArguments()); commandList.add(outputFile.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(commandList); // Needed for ffmpeg pb.environment().put("LD_LIBRARY_PATH", "/usr/local/lib:"); pb.redirectErrorStream(true); pb.directory(workingDirectory); Process process = null; try { // Get the ffmpeg 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("FFMPEG exit value: " + exitValue); if (exitValue != 0) { for (String line : result) { LOG.error(line); } throw new Exception("FFMpeg return code indicated failure: " + exitValue); } } catch (InterruptedException e) { throw new Exception("FFMpeg process interrupted by another thread", e); } catch (ExecutionException ee) { throw new Exception("Something went wrong parsing FFMpeg output", ee); } catch (TimeoutException te) { // We could not get the result before timeout throw new Exception("FFMpeg process timed out", te); } catch (RuntimeException re) { // Unexpected output from FFMpeg throw new Exception("Something went wrong parsing FFMpeg output", re); } finally { if (process != null) { process.destroy(); } } LOG.debug("transcoding finished"); }
From source file:com.netflix.genie.server.jobmanager.impl.PrestoJobManagerImpl.java
/** * Set up the process with specific Presto properties. * * @param processBuilder The process builder to modify. * @throws GenieException If there are any issues. *//*from w w w. jav a 2s .c o m*/ private void setupPrestoProcess(final ProcessBuilder processBuilder) throws GenieException { final Map<String, String> processEnv = processBuilder.environment(); processEnv.put("CP_TIMEOUT", ConfigurationManager.getConfigInstance() .getString("com.netflix.genie.server.hadoop.s3cp.timeout", "1800")); final String copyCommand = ConfigurationManager.getConfigInstance().getString(COPY_COMMAND_KEY); if (StringUtils.isBlank(copyCommand)) { final String msg = "Required property " + COPY_COMMAND_KEY + " isn't set"; LOG.error(msg); throw new GenieServerException(msg); } processEnv.put("COPY_COMMAND", copyCommand); final String makeDirCommand = ConfigurationManager.getConfigInstance().getString(MK_DIRECTORY_COMMAND_KEY); if (StringUtils.isBlank(makeDirCommand)) { final String msg = "Required property " + MK_DIRECTORY_COMMAND_KEY + " isn't set"; LOG.error(msg); throw new GenieServerException(msg); } processEnv.put("MKDIR_COMMAND", makeDirCommand); }
From source file:uk.ac.sanger.cgp.wwdocker.interfaces.Workflow.java
default int cleanDockerPath(BaseConfiguration config) { String command = baseDockerCommand(config, null); List<String> args = new ArrayList(Arrays.asList(command.split(" "))); args.add("/bin/bash"); args.add("-c"); args.add("rm -rf /datastore/oozie-* /datastore/*.ini /datastore/logs.tar.gz /datastore/toInclude.lst"); ProcessBuilder pb = new ProcessBuilder(args); Map<String, String> pEnv = pb.environment(); pEnv.putAll(Config.getEnvs(config)); logger.info("Executing: " + String.join(" ", args)); int exitCode = -1; Process p = null;//from w w w . java 2 s. c om try { p = pb.start(); String progErr = IOUtils.toString(p.getErrorStream()); String progOut = IOUtils.toString(p.getInputStream()); exitCode = p.waitFor(); Utils.logOutput(progErr, Level.ERROR); Utils.logOutput(progOut, Level.TRACE); } catch (InterruptedException | IOException e) { logger.error(e.getMessage(), e); } finally { if (p != null) { p.destroy(); exitCode = p.exitValue(); } } return exitCode; }