List of usage examples for java.lang ProcessBuilder redirectOutput
public ProcessBuilder redirectOutput(File file)
From source file:actors.ConfigUtil.java
static ProcessBuilder buildProcess(String javaCmd, String etlJobName, long whEtlExecId, String cmdParam, Properties etlJobProperties) { String classPath = System.getProperty("java.class.path"); String outDir = etlJobProperties.getProperty(Constant.WH_APP_FOLDER_KEY, WH_APPLICATION_DEFAULT_DIRECTORY); String configFile = outDir + "/" + whEtlExecId + ".properties"; String[] cmdParams = isNotBlank(cmdParam) ? cmdParam.trim().split(" ") : new String[0]; ProcessBuilder pb = new ProcessBuilder(new ImmutableList.Builder<String>().add(javaCmd) .addAll(Arrays.asList(cmdParams)).add("-cp").add(classPath).add("-Dconfig=" + configFile) .add("-DCONTEXT=" + etlJobName).add("-Dlogback.configurationFile=etl_logback.xml") .add("-DLOG_DIR=" + outDir).add(Launcher.class.getCanonicalName()).build()); pb.redirectOutput(ProcessBuilder.Redirect.to(new File(outDir + "/stdout"))); pb.redirectError(ProcessBuilder.Redirect.to(new File(outDir + "/stderr"))); return pb;/*from w ww . ja va 2 s . c o m*/ }
From source file:alluxio.cli.ValidateEnv.java
private static boolean validateRemote(String node, String target, String name, CommandLine cmd) throws InterruptedException { System.out.format("Validating %s environment on %s...%n", target, node); if (!Utils.isAddressReachable(node, 22)) { System.err.format("Unable to reach ssh port 22 on node %s.%n", node); return false; }//w ww . j a v a 2s . co m // args is not null. String argStr = String.join(" ", cmd.getArgs()); String homeDir = Configuration.get(PropertyKey.HOME); String remoteCommand = String.format("%s/bin/alluxio validateEnv %s %s %s", homeDir, target, name == null ? "" : name, argStr); String localCommand = String.format( "ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no -tt %s \"bash %s\"", node, remoteCommand); String[] command = { "bash", "-c", localCommand }; try { ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); builder.redirectOutput(ProcessBuilder.Redirect.INHERIT); builder.redirectInput(ProcessBuilder.Redirect.INHERIT); Process process = builder.start(); process.waitFor(); return process.exitValue() == 0; } catch (IOException e) { System.err.format("Unable to validate on node %s: %s.%n", node, e.getMessage()); return false; } }
From source file:org.dkpro.tc.ml.svmhmm.task.SVMHMMTestTask.java
/** * Executes the command (runs a new process outside the JVM and waits for its completion) * * @param command//from w w w . ja va2s .c om * command as list of Strings */ private static void runCommand(List<String> command) throws Exception { log.info(StringUtils.join(command, " ")); if (PRINT_STD_OUT) { Process process = new ProcessBuilder().inheritIO().command(command).start(); process.waitFor(); } else { // create temp files for capturing output instead of printing to // stdout/stderr File tmpOutLog = File.createTempFile("tmp.out.", ".log"); ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectError(tmpOutLog); processBuilder.redirectOutput(tmpOutLog); // run the process Process process = processBuilder.start(); process.waitFor(); // re-read the output and debug it BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tmpOutLog))); String line; while ((line = br.readLine()) != null) { log.debug(line); } IOUtils.closeQuietly(br); // delete files FileUtils.deleteQuietly(tmpOutLog); } }
From source file:at.ac.tuwien.dsg.cloud.salsa.engine.utils.SystemFunctions.java
/** * Run a command and wait//from ww w . j a va 2 s . com * * @param cmd The command to run * @param workingDir The folder where the command is run * @param executeFrom For logging message to the center of where to execute the command. * @return */ public static Process executeCommandAndForget(String cmd, String workingDir, String executeFrom) { logger.debug("Execute command: " + cmd); if (workingDir == null) { workingDir = "/tmp"; } String[] splitStr = cmd.split("\\s+"); ProcessBuilder pb = new ProcessBuilder(splitStr); pb.directory(new File(workingDir)); pb = pb.redirectErrorStream(true); // this is important to redirect the error stream to output stream, prevent blocking with long output pb.redirectOutput(new File("/tmp/salsa.conductor.log")); Map<String, String> env = pb.environment(); String path = env.get("PATH"); path = path + File.pathSeparator + "/usr/bin:/usr/sbin"; logger.debug("PATH to execute command: " + pb.environment().get("PATH")); env.put("PATH", path); Process p; try { p = pb.start(); return p; } catch (IOException ex) { logger.debug("Cannot run the command: " + cmd); return null; } }
From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.task.SVMHMMTestTask.java
/** * Executes the command (runs a new process outside the JVM and waits for its completion) * * @param command command as list of Strings *///from ww w. j a va2s . com private static void runCommand(List<String> command) throws Exception { log.info(StringUtils.join(command, " ")); if (PRINT_STD_OUT) { Process process = new ProcessBuilder().inheritIO().command(command).start(); process.waitFor(); } else { // create temp files for capturing output instead of printing to stdout/stderr File tmpOutLog = File.createTempFile("tmp.out.", ".log"); ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.redirectError(tmpOutLog); processBuilder.redirectOutput(tmpOutLog); // run the process Process process = processBuilder.start(); process.waitFor(); // re-read the output and debug it BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(tmpOutLog))); String line; while ((line = br.readLine()) != null) { log.debug(line); } IOUtils.closeQuietly(br); // delete files FileUtils.deleteQuietly(tmpOutLog); } }
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 va2 s .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:loadTest.loadTestLib.LUtil.java
public static boolean startDockerBuild() throws IOException, InterruptedException { if (useDocker) { if (runInDockerCluster) { HashMap<String, Integer> dockerNodes = getDockerNodes(); String dockerTar = LUtil.class.getClassLoader().getResource("docker/loadTest.tar").toString() .substring(5);/*from w ww . j a v a2 s . c om*/ ExecutorService exec = Executors.newFixedThreadPool(dockerNodes.size()); dockerError = false; doneDockers = 0; for (Entry<String, Integer> entry : dockerNodes.entrySet()) { exec.submit(new Runnable() { @Override public void run() { try { String url = entry.getKey() + "/images/vauvenal5/loadtest"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("DELETE"); con.setRequestProperty("force", "true"); int responseCode = con.getResponseCode(); con.disconnect(); url = entry.getKey() + "/build?t=vauvenal5/loadtest&dockerfile=./loadTest/Dockerfile"; obj = new URL(url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Content-type", "application/tar"); con.setDoOutput(true); File file = new File(dockerTar); FileInputStream fileStr = new FileInputStream(file); byte[] b = new byte[(int) file.length()]; fileStr.read(b); con.getOutputStream().write(b); con.getOutputStream().flush(); con.getOutputStream().close(); responseCode = con.getResponseCode(); if (responseCode != 200) { dockerError = true; } String msg = ""; do { Thread.sleep(5000); msg = ""; url = entry.getKey() + "/images/json"; obj = new URL(url); HttpURLConnection con2 = (HttpURLConnection) obj.openConnection(); con2.setRequestMethod("GET"); responseCode = con2.getResponseCode(); BufferedReader in = new BufferedReader( new InputStreamReader(con2.getInputStream())); String line = null; while ((line = in.readLine()) != null) { msg += line; } con2.disconnect(); } while (!msg.contains("vauvenal5/loadtest")); con.disconnect(); doneDockers++; } catch (MalformedURLException ex) { dockerError = true; } catch (FileNotFoundException ex) { dockerError = true; } catch (IOException ex) { dockerError = true; } catch (InterruptedException ex) { dockerError = true; } } }); } while (doneDockers < dockerNodes.size()) { Thread.sleep(5000); } return !dockerError; } //get the path and substring the 'file:' from the URI String dockerfile = LUtil.class.getClassLoader().getResource("docker/loadTest").toString().substring(5); ProcessBuilder processBuilder = new ProcessBuilder("docker", "rmi", "-f", "vauvenal5/loadtest"); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process docker = processBuilder.start(); docker.waitFor(); processBuilder = new ProcessBuilder("docker", "build", "-t", "vauvenal5/loadtest", dockerfile); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); Process proc = processBuilder.start(); return proc.waitFor() == 0; } return true; }
From source file:org.apache.spark.network.util.JavaUtils.java
private static void deleteRecursivelyUsingUnixNative(File file) throws IOException { ProcessBuilder builder = new ProcessBuilder("rm", "-rf", file.getAbsolutePath()); Process process = null;//from w ww .j a v a 2 s . c o m int exitCode = -1; try { // In order to avoid deadlocks, consume the stdout (and stderr) of the process builder.redirectErrorStream(true); builder.redirectOutput(new File("/dev/null")); process = builder.start(); exitCode = process.waitFor(); } catch (Exception e) { throw new IOException("Failed to delete: " + file.getAbsolutePath(), e); } finally { if (process != null) { process.destroy(); } } if (exitCode != 0 || file.exists()) { throw new IOException("Failed to delete: " + file.getAbsolutePath()); } }
From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java
private static List<String> system(ProcessBuilder.Redirect errorRedirector, ProcessBuilder.Redirect outputRedirector, String... command) { try {/* w ww . j ava 2 s.c o m*/ final ProcessBuilder builder = new ProcessBuilder(command); builder.redirectError(errorRedirector); builder.redirectOutput(outputRedirector); final Process process = builder.start(); Verify.verify(0 == process.waitFor(), "Process %s failed\n%s", Arrays.asList(command), IOUtils.toString(process.getErrorStream())); try (InputStream stream = process.getInputStream()) { return IOUtils.readLines(stream); } } catch (final Exception e) { throw Throwables.propagate(e); } }
From source file:jeplus.RadianceWinTools.java
/** * Call DaySim gen_dc to run the simulation * @param config Radiance Configuration/*from ww w. j a v a2 s . com*/ * @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; }