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:ca.uqac.info.Job.Launcher.JobLauncher.java
/** * Sets up the ProcessBuilder for the bat file and start it * @return The exitStatus //w ww.jav a 2s . c o m */ private static int launchJob(String fileBat, String outName, File outFolder) throws Exception { // The batch file to execute final File batchFile = new File(fileBat); // The output file. All activity is written to this file final File outputFile = new File(outName); // Create the process final ProcessBuilder processBuilder = new ProcessBuilder(batchFile.getAbsolutePath(), outName); // Redirect any output (including error) to a file. This avoids deadlocks // when the buffers get full. processBuilder.redirectErrorStream(true); processBuilder.redirectOutput(outputFile); // Add a new environment variable processBuilder.environment().put("JobLauncher", "Bat File Execution"); // Set the working directory. The batch file will run as if you are in this // directory. processBuilder.directory(outFolder); // Start the process and wait for it to finish. /* while(nextJob != true) { //Wait the end of the current Job to Launch the next one } nextJob = false;*/ final Process process = processBuilder.start(); final int exitStatus = process.waitFor(); process.destroy(); return exitStatus; }
From source file:org.jsweet.transpiler.util.ProcessUtil.java
/** * Runs the given command./*from www . ja v a 2 s . c o m*/ * * @param command * the command name * @param directory * the working directory of the created process * @param async * tells if the command should be run asynchronously (in a * separate thread) * @param stdoutConsumer * consumes the standard output stream as lines of characters * @param endConsumer * called when the process actually ends * @param errorHandler * upcalled when the command does not terminate successfully * @param args * the command-line arguments * @return the process that was created to execute the command (can be still * running at this point if <code>async</code> is <code>true</code>) */ public static Process runCommand(String command, File directory, boolean async, Consumer<String> stdoutConsumer, Consumer<Process> endConsumer, Runnable errorHandler, String... args) { String[] cmd; if (System.getProperty("os.name").startsWith("Windows")) { if (nodeCommands.contains(command)) { cmd = new String[] { getNpmPath(command) }; } else { cmd = new String[] { "cmd", "/c", command }; } } else { if (nodeCommands.contains(command)) { cmd = new String[] { getNpmPath(command) }; } else { cmd = new String[] { command }; } } cmd = ArrayUtils.addAll(cmd, args); logger.debug("run command: " + StringUtils.join(cmd, " ")); Process[] process = { null }; try { ProcessBuilder processBuilder = new ProcessBuilder(cmd); processBuilder.redirectErrorStream(true); if (directory != null) { processBuilder.directory(directory); } if (!StringUtils.isBlank(EXTRA_PATH)) { processBuilder.environment().put("PATH", processBuilder.environment().get("PATH") + File.pathSeparator + EXTRA_PATH); } process[0] = processBuilder.start(); Runnable runnable = new Runnable() { @Override public void run() { try { try (BufferedReader in = new BufferedReader( new InputStreamReader(process[0].getInputStream()))) { String line; while ((line = in.readLine()) != null) { if (stdoutConsumer != null) { stdoutConsumer.accept(line); } else { logger.info(command + " - " + line); } } } process[0].waitFor(); if (endConsumer != null) { endConsumer.accept(process[0]); } if (process[0].exitValue() != 0) { if (errorHandler != null) { errorHandler.run(); } } } catch (Exception e) { logger.error(e.getMessage(), e); if (errorHandler != null) { errorHandler.run(); } } } }; if (async) { new Thread(runnable).start(); } else { runnable.run(); } } catch (Exception e) { logger.error(e.getMessage(), e); if (errorHandler != null) { errorHandler.run(); } return null; } return process[0]; }
From source file:jeplus.RadianceWinTools.java
/** * Call Rtrace to run the simulation/*from w w w . j av a 2s .c o m*/ * @param config Radiance Configuration * @param WorkDir The working directory where the input files are stored and the output files to be generated * @param args * @param model * @param in * @param out * @param err * @param process * @return the result code represents the state of execution steps. >=0 means successful */ public static int runRtrace(RadianceConfig config, String WorkDir, String args, String model, String in, String out, String err, ProcessWrapper process) { int ExitValue = -99; try { StringBuilder buf = new StringBuilder(config.getResolvedRadianceBinDir()); buf.append(File.separator).append("rtrace"); List<String> command = new ArrayList<>(); command.add(buf.toString()); String[] arglist = args.split("\\s+"); command.addAll(Arrays.asList(arglist)); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir()); builder.redirectError(new File(WorkDir + File.separator + err)); builder.redirectOutput(new File(WorkDir + File.separator + out)); builder.redirectInput(new File(WorkDir + File.separator + in)); Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing Rtrace", ex); } // Return Radiance exit value return ExitValue; }
From source file:com.asakusafw.runtime.util.hadoop.ConfigurationProvider.java
private static File detectHadoopConfigurationDirectory(File command, File temporary, Map<String, String> envp) throws IOException { assert command != null; assert temporary != null; assert envp != null; prepareClasspath(temporary, ConfigurationDetecter.class); File resultOutput = new File(temporary, PATH_SUBPROC_OUTPUT); List<String> arguments = new ArrayList<>(); arguments.add(command.getAbsolutePath()); arguments.add(ConfigurationDetecter.class.getName()); arguments.add(resultOutput.getAbsolutePath()); ProcessBuilder processBuilder = new ProcessBuilder(arguments); processBuilder.environment().clear(); processBuilder.environment().putAll(envp); processBuilder.environment().put(ENV_HADOOP_CLASSPATH, temporary.getPath()); Process process = processBuilder.start(); try {// w ww . j a va 2 s . co m Thread redirectOut = redirect(process.getInputStream(), System.out); Thread redirectErr = redirect(process.getErrorStream(), System.err); try { int exit = process.waitFor(); redirectOut.join(); redirectErr.join(); if (exit != 0) { throw new IOException( MessageFormat.format("Failed to execute Hadoop command (exitcode={1}): {0}", arguments, String.valueOf(exit))); } } catch (InterruptedException e) { throw (IOException) new InterruptedIOException( MessageFormat.format("Failed to execute Hadoop command (interrupted): {0}", arguments)) .initCause(e); } } finally { process.destroy(); } if (resultOutput.isFile() == false) { throw new IOException( MessageFormat.format("Failed to restore Hadoop configuration path: {0}", resultOutput)); } File path = ConfigurationDetecter.read(resultOutput); return path; }
From source file:jeplus.RadianceWinTools.java
/** * Call DaySim gen_dc to run the simulation * @param config Radiance Configuration/*from w w w .j av a 2 s . c om*/ * @param WorkDir The working directory where the input files are stored and the output files to be generated * @param model * @param in * @param out * @param err * @param process * @return the result code represents the state of execution steps. >=0 means successful */ public static int runGen_DC(RadianceConfig config, String WorkDir, String model, String in, String out, String err, ProcessWrapper process) { int ExitValue = -99; // Manipulate header file HashMap<String, String> props = new HashMap<>(); // props.put("project_name", ""); props.put("project_directory", "./"); props.put("bin_directory", config.getResolvedDaySimBinDir()); props.put("tmp_directory", "./"); props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/"); props.put("sensor_file", in); try { FileUtils.moveFile(new File(WorkDir + File.separator + model), new File(WorkDir + File.separator + model + ".ori")); } catch (IOException ex) { logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex); } DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model, props); // Run command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("gen_dc"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectOutput(new File(WorkDir + File.separator + out)); if (err == null || out.equals(err)) { builder.redirectErrorStream(true); } else { builder.redirectError(new File(WorkDir + File.separator + err)); } if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing DaySim gen_dc", ex); } // Return Radiance exit value return ExitValue; }
From source file:com.ikanow.aleph2.analytics.spark.utils.SparkTechnologyUtils.java
/** Creates a command line call to launch spark * @param spark_home/*from w ww.j av a2 s . c o m*/ * @param yarn_home * @param spark_master * @param main_clazz * @param context_signature * @param main_jar * @param other_jars * @param spark_job_options * @param spark_system_options */ public static ProcessBuilder createSparkJob(final String job_name, final String spark_home, final String yarn_home, final String spark_master, final Optional<String> maybe_main_clazz, final String context_signature, final Optional<String> test_signature, final String main_jar_or_py, final Collection<String> other_jars, final Collection<String> other_files, final Collection<String> other_lang_files, final List<String> external_jars, final List<String> external_files, final List<String> external_lang_files, final Optional<Map<String, Object>> spark_generic_options, final Map<String, String> spark_job_options, final Map<String, String> spark_system_options ) { //https://spark.apache.org/docs/1.2.0/submitting-applications.html final List<String> command_line = ImmutableList.<String>builder().add(SBT_SUBMIT_BINARY).add("--name") .add(job_name) .addAll(maybe_main_clazz.map(main_clazz -> Arrays.asList("--class", main_clazz)) .orElse(Collections.emptyList())) .add("--master").add(spark_master).add("--jars") .add(Stream.concat(other_jars.stream(), external_jars.stream()).collect(Collectors.joining(","))) .addAll(Optional .of(Stream.concat(other_files.stream(), external_files.stream()) .collect(Collectors.joining(","))) .filter(s -> !s.isEmpty()).map(s -> Arrays.asList("--files", s)) .orElse(Collections.emptyList())) //TODO (ALEPH-63): handle R in the example below .addAll(Optional .of(Stream.concat(other_lang_files.stream(), external_lang_files.stream()) .collect(Collectors.joining(","))) .filter(s -> !s.isEmpty()).map(s -> Arrays.asList("--py-files", s)) .orElse(Collections.emptyList())) .addAll(Optional.ofNullable(System.getProperty("hdp.version")).map(hdp_version -> { // Set HDP version from whatever I'm set to return (List<String>) ImmutableList.<String>of("--conf", "spark.executor.extraJavaOptions=-Dhdp.version=" + hdp_version, "--conf", "spark.driver.extraJavaOptions=-Dhdp.version=" + hdp_version, "--conf", "spark.yarn.am.extraJavaOption=-Dhdp.version=" + hdp_version); }).orElse(Collections.emptyList())) .addAll(spark_job_options.isEmpty() ? Collections.emptyList() : spark_job_options.entrySet().stream() .flatMap(kv -> Stream.of("--conf", kv.getKey() + "=" + kv.getValue())) .collect(Collectors.toList())) .addAll(spark_system_options.entrySet().stream() .flatMap(kv -> Stream.of(kv.getKey(), kv.getValue())).collect(Collectors.toList())) .addAll(spark_generic_options.map(opts -> Arrays.asList("--conf", SparkTopologyConfigBean.JOB_CONFIG_KEY + "=" + BeanTemplateUtils.configureMapper(Optional.empty()).convertValue(opts, JsonNode.class))) .orElse(Collections.emptyList())) .add(main_jar_or_py).add(context_signature) .addAll(test_signature.map(ts -> Arrays.asList(ts)).orElse(Collections.emptyList())).build(); final ProcessBuilder pb = new ProcessBuilder(); final Map<String, String> mutable_env = pb.environment(); mutable_env.put("HADOOP_CONF_DIR", yarn_home); return pb.directory(new File(spark_home)).command(command_line); }
From source file:jeplus.RadianceWinTools.java
/** * Call a sequence of DaySim programs to run the simulation * @param config Radiance Configuration// w ww. jav a2s.c o m * @param WorkDir The working directory where the input files are stored and the output files to be generated * @param model * @param in * @param out * @param err * @param process * @return the result code represents the state of execution steps. >=0 means successful */ public static int runDaySim(RadianceConfig config, String WorkDir, String model, String in, String out, String err, ProcessWrapper process) { int ExitValue = -99; // Manipulate header file HashMap<String, String> props = new HashMap<>(); // props.put("project_name", ""); props.put("project_directory", "./"); props.put("bin_directory", config.getResolvedDaySimBinDir()); props.put("tmp_directory", "./"); props.put("Template_File", config.getResolvedDaySimBinDir() + "../template/DefaultTemplate.htm"); props.put("sensor_file", in); try { FileUtils.moveFile(new File(WorkDir + File.separator + model), new File(WorkDir + File.separator + model + ".ori")); } catch (IOException ex) { logger.error("Error renaming header file to " + WorkDir + File.separator + model + ".ori", ex); } DaySimModel.updateHeaderFile(WorkDir + File.separator + model + ".ori", WorkDir + File.separator + model, props); // Run gen_dc command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("gen_dc"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectError(new File(WorkDir + File.separator + err)); builder.redirectOutput(new File(WorkDir + File.separator + out)); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing gen_dc", ex); } // Run ds_illum command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("ds_illum"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectError(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err))); builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + out))); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing ds_illum", ex); } // Run ds_el_lighting command try { StringBuilder buf = new StringBuilder(config.getResolvedDaySimBinDir()); buf.append(File.separator).append("ds_el_lighting"); List<String> command = new ArrayList<>(); command.add(buf.toString()); command.add(model); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedDaySimLibDir()); builder.redirectError(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err))); builder.redirectOutput(ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + out))); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing ds_el_lighting", ex); } // Return Radiance exit value return ExitValue; }
From source file:jeplus.RadianceWinTools.java
/** * Call Rpict to run the simulation//ww w.jav a 2 s . c om * @param config Radiance Configuration * @param WorkDir The working directory where the input files are stored and the output files to be generated * @param args * @param model * @param in * @param out * @param err * @param png Switch for converting scene to jpg or not * @param process * @return the result code represents the state of execution steps. >=0 means successful */ public static int runRpict(RadianceConfig config, String WorkDir, String args, String model, String in, String out, String err, boolean png, ProcessWrapper process) { int ExitValue = -99; // Call rpict StringBuilder buf = new StringBuilder(config.getResolvedRadianceBinDir()); buf.append(File.separator).append("rpict"); List<String> command = new ArrayList<>(); command.add(buf.toString()); String[] arglist = args.split("\\s+"); command.addAll(Arrays.asList(arglist)); command.add(model); try { ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir()); builder.redirectError(new File(WorkDir + File.separator + err)); builder.redirectOutput(new File(WorkDir + File.separator + out)); if (in != null) { builder.redirectInput(new File(WorkDir + File.separator + in)); } Process proc = builder.start(); if (process != null) { process.setWrappedProc(proc); } ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing Rpict", ex); } if (png) { // Sweep everything with the same extension as out. This is for handling // -o option in rpict String ext = FilenameUtils.getExtension(out); File[] files = new File(WorkDir).listFiles((FileFilter) new WildcardFileFilter("*." + ext)); for (File file : files) { String outname = file.getName(); // Filter scene try { buf = new StringBuilder(config.getResolvedRadianceBinDir()); buf.append(File.separator).append("pfilt"); command = new ArrayList<>(); command.add(buf.toString()); // String [] arglist = "-1 -e -3".split("\\s+"); // command.addAll(Arrays.asList(arglist)); command.add(outname); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir()); builder.redirectError(new File(WorkDir + File.separator + err)); builder.redirectOutput(new File(WorkDir + File.separator + outname + ".flt")); Process proc = builder.start(); ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing pfilt", ex); } // Convert to bmp try { buf = new StringBuilder(config.getResolvedRadianceBinDir()); buf.append(File.separator).append("ra_bmp"); command = new ArrayList<>(); command.add(buf.toString()); //String [] arglist = "-g 1.0".split("\\s+"); //command.addAll(Arrays.asList(arglist)); command.add(outname + ".flt"); command.add(outname + ".bmp"); ProcessBuilder builder = new ProcessBuilder(command); builder.directory(new File(WorkDir)); builder.environment().put("RAYPATH", "." + File.pathSeparator + config.getResolvedRadianceLibDir()); builder.redirectError( ProcessBuilder.Redirect.appendTo(new File(WorkDir + File.separator + err))); Process proc = builder.start(); ExitValue = proc.waitFor(); } catch (IOException | InterruptedException ex) { logger.error("Error occoured when executing ra_bmp", ex); } // Convert to png BufferedImage input_image = null; try { input_image = ImageIO.read(new File(WorkDir + File.separator + outname + ".bmp")); //read bmp into input_image object File outputfile = new File(WorkDir + File.separator + outname + ".png"); //create new outputfile object ImageIO.write(input_image, "png", outputfile); //write PNG output to file } catch (Exception ex) { logger.error("Error converting bmp to png.", ex); } // Remove flt and bmp new File(WorkDir + File.separator + outname + ".flt").delete(); new File(WorkDir + File.separator + outname + ".bmp").delete(); } } // Return Radiance exit value return ExitValue; }
From source file:org.cloudifysource.azure.AbstractCliAzureDeploymentTest.java
public static String runCliCommands(File cliExecutablePath, List<List<String>> commands, boolean isDebug) throws IOException, InterruptedException { if (!cliExecutablePath.isFile()) { throw new IllegalArgumentException(cliExecutablePath + " is not a file"); }/* w ww. j a v a 2 s. c om*/ File workingDirectory = cliExecutablePath.getAbsoluteFile().getParentFile(); if (!workingDirectory.isDirectory()) { throw new IllegalArgumentException(workingDirectory + " is not a directory"); } int argsCount = 0; for (List<String> command : commands) { argsCount += command.size(); } // needed to properly intercept error return code String[] cmd = new String[(argsCount == 0 ? 0 : 1) + 4 /* cmd /c call cloudify.bat ["args"] */]; int i = 0; cmd[i] = "cmd"; i++; cmd[i] = "/c"; i++; cmd[i] = "call"; i++; cmd[i] = cliExecutablePath.getAbsolutePath(); i++; if (argsCount > 0) { cmd[i] = "\""; //TODO: Use StringBuilder for (List<String> command : commands) { if (command.size() > 0) { for (String arg : command) { if (cmd[i].length() > 0) { cmd[i] += " "; } cmd[i] += arg; } cmd[i] += ";"; } } cmd[i] += "\""; } final ProcessBuilder pb = new ProcessBuilder(cmd); pb.directory(workingDirectory); pb.redirectErrorStream(true); String extCloudifyJavaOptions = ""; if (isDebug) { extCloudifyJavaOptions += "-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=9000 -Xnoagent -Djava.compiler=NONE"; } pb.environment().put("EXT_CLOUDIFY_JAVA_OPTIONS", extCloudifyJavaOptions); final StringBuilder sb = new StringBuilder(); logger.info("running: " + cliExecutablePath + " " + Arrays.toString(cmd)); // log std output and redirected std error Process p = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = reader.readLine(); while (line != null) { sb.append(line).append('\n'); line = reader.readLine(); logger.info(line); } final String readResult = sb.toString(); final int exitValue = p.waitFor(); logger.info("Exit value = " + exitValue); if (exitValue != 0) { Assert.fail("Cli ended with error code: " + exitValue); } return readResult; }
From source file:com.thoughtworks.cruise.util.command.CommandLine.java
public static void setEnvironmentVariables(ProcessBuilder pb, EnvironmentVariableContext environmentVariableContext, ConsoleOutputStreamConsumer consumer) { Map<String, String> env = pb.environment(); environmentVariableContext.setupRuntimeEnvironment(env, consumer); }