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:org.datacleaner.cli.JobTestHelper.java
private static String runJob(final File repository, final String jobName, final String... extraCliArgs) throws Exception { final String jobFileName = getAbsoluteFilename(repository, "jobs/" + jobName + ".analysis.xml"); final String confFileName = getAbsoluteFilename(repository, "conf.xml"); final String[] processBuilderArguments = ArrayUtils.addAll(new String[] { JAVA_EXECUTABLE, DATACLEANER_MAIN_CLASS_NAME, "-job", jobFileName, "-conf", confFileName }, extraCliArgs); final ProcessBuilder builder = new ProcessBuilder(processBuilderArguments); builder.environment().put("DATACLEANER_HOME", URLDecoder.decode(repository.getAbsolutePath(), "UTF-8")); builder.environment().put("CLASSPATH", System.getProperty("java.class.path")); final Process process = builder.start(); final StringBuilder result = new StringBuilder(); new Thread(() -> { try {//from ww w. jav a2 s . co m final InputStream is = process.getInputStream(); int character; while ((character = is.read()) != -1) { result.append((char) character); } } catch (IOException e) { e.printStackTrace(); } }).start(); assertEquals(0, process.waitFor()); return result.toString(); }
From source file:jp.co.tis.gsp.tools.dba.util.ProcessUtil.java
public static void exec(Map<String, String> environment, String... args) throws IOException, InterruptedException { Process process = null;/*www . ja v a2s . co m*/ InputStream stdout = null; BufferedReader br = null; try { ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(true); if (environment != null) { pb.environment().putAll(environment); } process = pb.start(); stdout = process.getInputStream(); br = new BufferedReader(new InputStreamReader(stdout)); String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { throw e; } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(stdout); if (process != null) { process.destroy(); } } }
From source file:Main.java
/** * create a child process with environment variables * @param command/*from w w w . ja va 2 s .c om*/ * @param envVars * @return * @throws InterruptedException * @throws IOException */ public static String execUnixCommand(String[] command, Map<String, String> envVars) throws InterruptedException, IOException { /* ProcessBuilder processBuilder = new ProcessBuilder(command); if ( envVars != null ){ Map<String, String> env = processBuilder.environment(); env.clear(); env.putAll(envVars); } Process process = processBuilder.start(); processBuilder.redirectErrorStream(false); process.waitFor(); String outputWithError = loadStream(process.getInputStream()) + loadStream(process.getErrorStream()); return outputWithError; */ ProcessBuilder processBuilder = new ProcessBuilder(command); if (envVars != null) { Map<String, String> env = processBuilder.environment(); env.clear(); env.putAll(envVars); } Process process = processBuilder.start(); String output = loadStream(process.getInputStream()); String error = loadStream(process.getErrorStream()); process.waitFor(); return output + "\n" + error; }
From source file:org.scribble.cli.ExecUtil.java
/** * Runs a process, up to a certain timeout, * //from w w w. j av a 2 s . com * @throws IOException * @throws TimeoutException * @throws ExecutionException * @throws InterruptedException */ public static ProcessSummary execUntil(Map<String, String> env, long timeout, String... command) throws IOException, InterruptedException, ExecutionException { ProcessBuilder builder = new ProcessBuilder(command); builder.environment().putAll(env); Process process = builder.start(); ExecutorService executorService = Executors.newFixedThreadPool(3); CyclicBarrier onStart = new CyclicBarrier(3); Future<String> stderr = executorService.submit(toString(process.getErrorStream(), onStart)); Future<String> stdout = executorService.submit(toString(process.getInputStream(), onStart)); Future<Integer> waitFor = executorService.submit(waitFor(process, onStart)); ProcessSummary result = null; try { waitFor.get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException e) { // timeouts are ok } finally { process.destroy(); waitFor.get(); result = new ProcessSummary(stdout.get(), stderr.get(), process.exitValue()); executorService.shutdown(); } return result; }
From source file:io.jmnarloch.cd.go.plugin.gradle.GradleTaskExecutor.java
/** * Builds the Gradle process for later execution, it configures all the build properties based on the current * task configuration. It also takes into account the current task execution context. * * @param config the task configuration/*w ww . j a va2 s. c o m*/ * @param environment the task execution environment * @return the created Gradle build process */ private static ProcessBuilder buildGradleProcess(ExecutionConfiguration config, ExecutionContext environment) { final Map<String, String> env = environment.getEnvironmentVariables(); String workingDirectory = unifyPath(environment.getWorkingDirectory()); workingDirectory = workingDirectory.endsWith(File.separator) ? workingDirectory : workingDirectory + File.separator; String relativePath = config.getProperty(GradleTaskConfig.RELATIVE_PATH.getName()); workingDirectory = StringUtils.isBlank(relativePath) ? workingDirectory : unifyPath(workingDirectory + relativePath); final List<String> command = parse(config, env, workingDirectory); logger.debug("Executing command: " + command); final ProcessBuilder builder = new ProcessBuilder(command); builder.environment().putAll(env); builder.directory(new File(workingDirectory)); return builder; }
From source file:org.esa.s2tbx.dataio.openjpeg.OpenJpegUtils.java
public static CommandOutput runProcess(ProcessBuilder builder) throws InterruptedException, IOException { builder.environment().putAll(System.getenv()); StringBuilder output = new StringBuilder(); boolean isStopped = false; final Process process = builder.start(); try (BufferedReader outReader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while (!isStopped) { while (outReader.ready()) { String line = outReader.readLine(); if (line != null && !line.isEmpty()) { output.append(line); }/* w w w . ja v a 2 s. c om*/ } if (!process.isAlive()) { isStopped = true; } else { Thread.yield(); } } outReader.close(); } int exitCode = process.exitValue(); //String output = convertStreamToString(process.getInputStream()); String errorOutput = convertStreamToString(process.getErrorStream()); return new CommandOutput(exitCode, output.toString(), errorOutput); }
From source file:de.bamamoto.mactools.png2icns.Scaler.java
protected static String runProcess(String[] commandLine) throws IOException { StringBuilder cl = new StringBuilder(); for (String i : commandLine) { cl.append(i);/*from www.j a v a 2 s .co m*/ cl.append(" "); } String result = ""; ProcessBuilder builder = new ProcessBuilder(commandLine); Map<String, String> env = builder.environment(); env.put("PATH", "/usr/sbin:/usr/bin:/sbin:/bin"); builder.redirectErrorStream(true); Process process = builder.start(); String line; InputStream stdout = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stdout)); while ((line = reader.readLine()) != null) { result += line + "\n"; } boolean isProcessRunning = true; int maxRetries = 60; do { try { isProcessRunning = process.exitValue() < 0; } catch (IllegalThreadStateException ex) { System.out.println("Process not terminated. Waiting ..."); try { Thread.sleep(1000); } catch (InterruptedException iex) { //nothing todo } maxRetries--; } } while (isProcessRunning && maxRetries > 0); System.out.println("Process has terminated"); if (process.exitValue() != 0) { throw new IllegalStateException("Exit value not equal to 0: " + result); } if (maxRetries == 0 && isProcessRunning) { System.out.println("Process does not terminate. Try to kill the process now."); process.destroy(); } return result; }
From source file:org.apache.storm.daemon.supervisor.ClientSupervisorUtils.java
/** * Launch a new process as per {@link ProcessBuilder} with a given * callback./*from ww w. ja va2 s .co m*/ * @param command the command to be executed in the new process * @param environment the environment to be applied to the process. Can be * null. * @param logPrefix a prefix for log entries from the output of the process. * Can be null. * @param exitCodeCallback code to be called passing the exit code value * when the process completes * @param dir the working directory of the new process * @return the new process * @throws IOException * @see ProcessBuilder */ public static Process launchProcess(List<String> command, Map<String, String> environment, final String logPrefix, final ExitCodeCallback exitCodeCallback, File dir) throws IOException { ProcessBuilder builder = new ProcessBuilder(command); Map<String, String> procEnv = builder.environment(); if (dir != null) { builder.directory(dir); } builder.redirectErrorStream(true); if (environment != null) { procEnv.putAll(environment); } final Process process = builder.start(); if (logPrefix != null || exitCodeCallback != null) { Utils.asyncLoop(new Callable<Object>() { public Object call() { if (logPrefix != null) { Utils.readAndLogStream(logPrefix, process.getInputStream()); } if (exitCodeCallback != null) { try { process.waitFor(); exitCodeCallback.call(process.exitValue()); } catch (InterruptedException ie) { LOG.info("{} interrupted", logPrefix); exitCodeCallback.call(-1); } } return null; // Run only once. } }); } return process; }
From source file:gool.executor.Command.java
/** * Executes a command in the specified working directory. * //from www . j a v a 2s .co m * @param workingDir * the working directory. * @param params * the command to execute and its parameters. * @return the console output. */ public static String exec(File workingDir, List<String> params, Map<String, String> env) { try { StringBuffer buffer = new StringBuffer(); ProcessBuilder pb = new ProcessBuilder(params); pb.directory(workingDir); for (Entry<String, String> e : env.entrySet()) { pb.environment().put(e.getKey(), e.getValue()); } Process p = pb.redirectErrorStream(true).start(); p.getOutputStream().close(); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = in.readLine()) != null) { buffer.append(line).append("\n"); } int retval = p.waitFor(); if (retval != 0) { throw new CommandException( "The command execution returned " + retval + " as return value... !\n" + buffer); } return buffer.toString(); } catch (IOException e) { throw new CommandException(e); } catch (InterruptedException e) { throw new CommandException("It seems the process was killed", e); } }
From source file:org.apache.pig.impl.streaming.StreamingUtil.java
/** * Set up the run-time environment of the managed process. * /*w w w . j av a 2s . c o m*/ * @param pb * {@link ProcessBuilder} used to exec the process */ private static void setupEnvironment(ProcessBuilder pb) { String separator = ":"; Configuration conf = UDFContext.getUDFContext().getJobConf(); Map<String, String> env = pb.environment(); addJobConfToEnvironment(conf, env); // Add the current-working-directory to the $PATH File dir = pb.directory(); String cwd = (dir != null) ? dir.getAbsolutePath() : System.getProperty("user.dir"); String envPath = env.get(PATH); if (envPath == null) { envPath = cwd; } else { envPath = envPath + separator + cwd; } env.put(PATH, envPath); }