List of usage examples for java.lang ProcessBuilder directory
File directory
To view the source code for java.lang ProcessBuilder directory.
Click Source Link
From source file:jeplus.RadianceWinTools.java
/** * Call a sequence of DaySim programs to run the simulation * @param config Radiance Configuration/*from w w w .j a va 2s . 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 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/*w w w . j ava2s .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.renjin.primitives.System.java
@Internal("system") public static SEXP system(@Current Context context, String command, int flag, SEXP stdin, SEXP stdout, SEXP stderr) throws IOException, InterruptedException { boolean invisible = (flag >= 20 && flag < 29); boolean minimized = (flag >= 10 && flag < 19); List<String> args = parseArgs(command); ProcessBuilder builder = new ProcessBuilder(args); FileObject workingDir = context.getSession().getWorkingDirectory(); if (workingDir instanceof LocalFile) { File localDir = new File(workingDir.getURL().getFile()); builder.directory(localDir); }//from w w w . j a v a2s . co m Process process = builder.start(); process.waitFor(); int exitValue = process.exitValue(); return new IntArrayVector(exitValue); }
From source file:com.photon.phresco.framework.commons.ApplicationsUtil.java
public static List<PBXNativeTarget> getXcodeConfiguration(String projectCode) throws PhrescoException, JAXBException, IOException, PhrescoPomException { S_LOGGER.debug("Iphone technology target retrivel initiated"); StringBuilder builder = new StringBuilder(Utility.getProjectHome()); builder.append(projectCode);/* w ww. ja v a 2s .c o m*/ builder.append(File.separatorChar); builder.append(POM_XML); File pomPath = new File(builder.toString()); PomProcessor pomProcessor = new PomProcessor(pomPath); StringBuilder projPath = new StringBuilder(Utility.getProjectHome()); projPath.append(projectCode); projPath.append(pomProcessor.getSourceDirectory()); File file = new File(projPath.toString()); FilenameFilter filter = new FileListFilter("", IPHONE_XCODE_PROJ_EXTN); File[] listFiles = file.listFiles(filter); projPath.append(File.separator); // Get firest xcode proj file name projPath.append(listFiles[0].getName()); S_LOGGER.debug("Iphone technology listFile name" + listFiles[0].getName()); String pbxprojLocation = projPath.toString(); // plutil location in mac File plutilCommandLine = new File("/usr/bin/plutil"); List<PBXNativeTarget> targets = null; S_LOGGER.debug("Before entering plutilCommandLine "); if (!plutilCommandLine.exists()) { S_LOGGER.debug("Invalid path for plutil"); throw new PhrescoException("Invalid path for plutil"); } File xcodeprojJson = new File(pbxprojLocation, "xcodeInfo.json"); S_LOGGER.debug("Before plutil try!!!"); try { String[] commands = { "plutil", "-convert", "json", "-o", xcodeprojJson.getAbsolutePath(), pbxprojLocation + "/project.pbxproj" }; ProcessBuilder probuilder = new ProcessBuilder(commands); probuilder.directory(new File(pbxprojLocation)); probuilder.start(); } catch (Exception e) { S_LOGGER.error("Error While Executing" + e); throw new PhrescoException("Error while executing "); } S_LOGGER.error("Before While loop"); while (!xcodeprojJson.exists()) { } S_LOGGER.error("After While loop Completed"); if (xcodeprojJson.exists()) { S_LOGGER.error("File exists"); XcodeprojParser parser = new XcodeprojParser(xcodeprojJson); try { PBXProject project = parser.parseXcodeFile(); if (project != null) { targets = project.getTargets(); } } catch (Exception e) { throw new PhrescoException(e); } } S_LOGGER.error("File reading completed"); xcodeprojJson.delete(); S_LOGGER.debug("Going to return from applications util"); return targets; }
From source file:org.fiware.cybercaptor.server.api.InformationSystemManagement.java
/** * Execute MulVAL on the topology and return the attack graph * * @return the associated attack graph object *///w ww .j a v a 2 s. c om public static AttackGraph generateAttackGraphWithMulValUsingAlreadyGeneratedMulVALInputFile() { try { //Load MulVAL properties String mulvalPath = ProjectProperties.getProperty("mulval-path"); String xsbPath = ProjectProperties.getProperty("xsb-path"); String outputFolderPath = ProjectProperties.getProperty("output-path"); File mulvalInputFile = new File(ProjectProperties.getProperty("mulval-input")); File mulvalOutputFile = new File(outputFolderPath + "/AttackGraph.xml"); if (mulvalOutputFile.exists()) { mulvalOutputFile.delete(); } Logger.getAnonymousLogger().log(Level.INFO, "Launching MulVAL"); ProcessBuilder processBuilder = new ProcessBuilder(mulvalPath + "/utils/graph_gen.sh", mulvalInputFile.getAbsolutePath(), "-l"); if (ProjectProperties.getProperty("mulval-rules-path") != null) { processBuilder.command().add("-r"); processBuilder.command().add(ProjectProperties.getProperty("mulval-rules-path")); } processBuilder.directory(new File(outputFolderPath)); processBuilder.environment().put("MULVALROOT", mulvalPath); String path = System.getenv("PATH"); processBuilder.environment().put("PATH", mulvalPath + "/utils/:" + xsbPath + ":" + path); Process process = processBuilder.start(); process.waitFor(); if (!mulvalOutputFile.exists()) { Logger.getAnonymousLogger().log(Level.INFO, "Empty attack graph!"); return null; } MulvalAttackGraph ag = new MulvalAttackGraph(mulvalOutputFile.getAbsolutePath()); return ag; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.fiware.cybercaptor.server.api.InformationSystemManagement.java
/** * Execute MulVAL on the topology and return the attack graph * * @param informationSystem the input network * @return the associated attack graph object *//*w w w. j a v a2 s . com*/ public static AttackGraph prepareInputsAndExecuteMulVal(InformationSystem informationSystem) { if (informationSystem == null) return null; try { //Load MulVAL properties String mulvalPath = ProjectProperties.getProperty("mulval-path"); String xsbPath = ProjectProperties.getProperty("xsb-path"); String outputFolderPath = ProjectProperties.getProperty("output-path"); File mulvalInputFile = new File(ProjectProperties.getProperty("mulval-input")); File mulvalOutputFile = new File(outputFolderPath + "/AttackGraph.xml"); if (mulvalOutputFile.exists()) { mulvalOutputFile.delete(); } Logger.getAnonymousLogger().log(Level.INFO, "Genering MulVAL inputs"); informationSystem.exportToMulvalDatalogFile(mulvalInputFile.getAbsolutePath()); Logger.getAnonymousLogger().log(Level.INFO, "Launching MulVAL"); ProcessBuilder processBuilder = new ProcessBuilder(mulvalPath + "/utils/graph_gen.sh", mulvalInputFile.getAbsolutePath(), "-l"); if (ProjectProperties.getProperty("mulval-rules-path") != null) { processBuilder.command().add("-r"); processBuilder.command().add(ProjectProperties.getProperty("mulval-rules-path")); } processBuilder.directory(new File(outputFolderPath)); processBuilder.environment().put("MULVALROOT", mulvalPath); String path = System.getenv("PATH"); processBuilder.environment().put("PATH", mulvalPath + "/utils/:" + xsbPath + ":" + path); Process process = processBuilder.start(); process.waitFor(); if (!mulvalOutputFile.exists()) { Logger.getAnonymousLogger().log(Level.INFO, "Empty attack graph!"); return null; } MulvalAttackGraph ag = new MulvalAttackGraph(mulvalOutputFile.getAbsolutePath()); ag.loadMetricsFromTopology(informationSystem); return ag; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.kylinolap.metadata.tool.HiveSourceTableMgmt.java
/** * @param hiveCommd//from www . j ava 2 s. c o m */ private static String callGenerateCommand(String hiveCommd) throws IOException { // Get out put path String tempDir = System.getProperty("java.io.tmpdir"); logger.info("OS current temporary directory is " + tempDir); if (StringUtils.isEmpty(tempDir)) { tempDir = "/tmp"; } String[] cmd = new String[2]; String osName = System.getProperty("os.name"); if (osName.startsWith("Windows")) { cmd[0] = "cmd.exe"; cmd[1] = "/C"; } else { cmd[0] = "/bin/bash"; cmd[1] = "-c"; } // hive command output // String hiveOutputPath = tempDir + File.separator + // "tmp_kylin_output"; String hiveOutputPath = File.createTempFile("HiveOutput", null).getAbsolutePath(); // Metadata output File dir = File.createTempFile("meta", null); dir.delete(); dir.mkdir(); String tableMetaOutcomeDir = dir.getAbsolutePath(); ProcessBuilder pb = null; if (osName.startsWith("Windows")) { pb = new ProcessBuilder(cmd[0], cmd[1], "ssh root@sandbox 'hive -e \"" + hiveCommd + "\"' > " + hiveOutputPath); } else { pb = new ProcessBuilder(cmd[0], cmd[1], "hive -e \"" + hiveCommd + "\" > " + hiveOutputPath); } // Run hive pb.directory(new File(tempDir)); pb.redirectErrorStream(true); Process p = pb.start(); InputStream is = p.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = null; try { br = new BufferedReader(isr); String line = null; logger.info("Execute : " + pb.command().get(0)); while ((line = br.readLine()) != null) { logger.info(line); } } finally { if (null != br) { br.close(); } } logger.info("Hive execution completed!"); HiveSourceTableMgmt rssMgmt = new HiveSourceTableMgmt(); rssMgmt.extractTableDescFromFile(hiveOutputPath, tableMetaOutcomeDir); return tableMetaOutcomeDir; }
From source file:com.ikanow.aleph2.analytics.spark.utils.SparkTechnologyUtils.java
/** Creates a command line call to launch spark * @param spark_home// w w w .j a va2s.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:ca.uqac.info.Job.Launcher.JobLauncher.java
/** * Sets up the ProcessBuilder for the bat file and start it * @return The exitStatus // w w w. j a v a2 s .c om */ 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:com.samsung.sjs.Compiler.java
public static Process exec(boolean should_inherit_io, String... args) throws IOException { System.err.println("Executing: " + Arrays.toString(args)); Path tmp = Files.createTempDirectory("testing"); tmp.toFile().deleteOnExit();/*from ww w .j a v a 2s.co m*/ ProcessBuilder pb = new ProcessBuilder(args); pb.directory(tmp.toFile()); if (should_inherit_io) { pb.inheritIO(); } return pb.start(); }