List of usage examples for java.lang ProcessBuilder redirectErrorStream
boolean redirectErrorStream
To view the source code for java.lang ProcessBuilder redirectErrorStream.
Click Source Link
From source file:org.schreibubi.JCombinationsTools.coordinatorPatch.CoordinatorPatch.java
private static void compile(String[] makecommand, boolean silent) throws IOException, InterruptedException, Exception { ProcessBuilder pb = new ProcessBuilder(makecommand); // Map< String, String > en = pb.environment(); /*/*from www .j ava2 s. c o m*/ * for ( String string : en.keySet() ) { System.out.println( string + "=" + en.get( string ) ); } */ pb.redirectErrorStream(true); Process p = pb.start(); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); if (!silent) { String c; while ((c = br.readLine()) != null) { System.out.println(c); } } p.waitFor(); int retVal = p.exitValue(); if (retVal != 0) throw new Exception("Compilation failed!"); }
From source file:org.openo.nfvo.jujuvnfmadapter.common.EntityUtils.java
/** * execute local command// w w w . j ava2 s . c om * <br/> * * @param dir the command path * @param command * @return response msg * @since NFVO 0.5 */ public static ExeRes execute(String dir, List<String> command) { ExeRes er = new ExeRes(); StringBuilder sb = new StringBuilder(); try { if (SwitchController.isDebugModel()) { String resContent = new String( FileUtils.readFile(new File(JujuConfigUtil.getValue("juju_cmd_res_file")), "UTF-8")); er.setBody(resContent); return er; } ProcessBuilder pb = new ProcessBuilder(command); if (StringUtils.isNotBlank(dir)) { pb.directory(new File(dir)); } pb.redirectErrorStream(true); Process p = pb.start(); // wait the process result buildProcessResult(er, p); InputStream in = p.getInputStream(); byte[] buffer = new byte[1024]; int length; while ((length = in.read(buffer)) > 0) { sb.append(new String(buffer, 0, length)); } in.close(); er.setBody(sb.toString()); } catch (Exception e) { er.setCode(ExeRes.FAILURE); er.setBody(e.getMessage()); LOG.error("execute the command failed:{}", command, e); } return er; }
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 w w. j a va 2 s . c o m 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:org.oxymores.chronix.engine.RunnerShell.java
public static RunResult run(RunDescription rd, String logFilePath, boolean storeLogFile, boolean returnFullerLog) { RunResult res = new RunResult(); Process p;//from ww w . j av a2 s . c o m String nl = System.getProperty("line.separator"); Pattern pat = Pattern.compile("^set ([a-zA-Z]+[a-zA-Z0-9]*)=(.+)"); Matcher matcher = pat.matcher("Testing123Testing"); String encoding = getEncoding(rd); log.debug("Encoding is " + encoding); // /////////////////////////// // Build command List<String> argsStrings = buildCommand(rd); // ///////////////////////////////////////////////////////////////////////// // Create a process builder with the command line contained in the array ProcessBuilder pb = new ProcessBuilder(argsStrings); // Mix stdout and stderr (easier to put errors in context this way) pb.redirectErrorStream(true); // Create array containing environment Map<String, String> env = pb.environment(); for (int i = 0; i < rd.getEnvNames().size(); i++) { env.put(rd.getEnvNames().get(i), rd.getEnvValues().get(i)); } BufferedReader br = null; Writer output = null; try { // Start! log.debug("GO (" + rd.getSubMethod() + ")"); p = pb.start(); // Read output (err & out), write it to file InputStreamReader isr = new InputStreamReader(p.getInputStream(), encoding); br = new BufferedReader(isr); String line = null; int i = 0; LinkedHashMap<Integer, String> endBuffer = new LinkedHashMap<Integer, String>() { private static final long serialVersionUID = -6773540176968046737L; @Override protected boolean removeEldestEntry(java.util.Map.Entry<Integer, String> eldest) { return this.size() > Constants.MAX_RETURNED_BIG_LOG_END_LINES; } }; if (storeLogFile) { output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(logFilePath), "UTF-8")); } line = br.readLine(); while (line != null) { i++; // Local log file gets all lines if (storeLogFile) { output.write(line + nl); } // Small log gets first 500 lines or 10000 characters (the smaller of the two) if (i < Constants.MAX_RETURNED_SMALL_LOG_LINES && res.logStart.length() < Constants.MAX_RETURNED_SMALL_LOG_CHARACTERS) { res.logStart += nl + line; } // Scheduler internal log gets first line only if (i == 1) { log.debug(String.format("Job running. First line of output is: %s", line)); } // Fuller log gets first 10k lines, then last 1k lines. if (returnFullerLog) { if (i < Constants.MAX_RETURNED_BIG_LOG_LINES) { res.fullerLog += line; } else { endBuffer.put(i, line); } } // Analysis: there may be a new variable definition in the line matcher.reset(line); if (matcher.find()) { log.debug("Key detected :" + matcher.group(1)); log.debug("Value detected :" + matcher.group(2)); res.newEnvVars.put(matcher.group(1), matcher.group(2)); } line = br.readLine(); } IOUtils.closeQuietly(br); if (i > Constants.MAX_RETURNED_BIG_LOG_LINES && i < Constants.MAX_RETURNED_BIG_LOG_LINES + Constants.MAX_RETURNED_BIG_LOG_END_LINES && returnFullerLog) { res.fullerLog += Arrays.toString(endBuffer.entrySet().toArray()); } if (i >= Constants.MAX_RETURNED_BIG_LOG_LINES + Constants.MAX_RETURNED_BIG_LOG_END_LINES && returnFullerLog) { res.fullerLog += "\n\n\n*******\n LOG TRUNCATED - See full log on server\n********\n\n\n" + Arrays.toString(endBuffer.entrySet().toArray()); } // Done: close log file if (storeLogFile) { IOUtils.closeQuietly(output); File f = new File(logFilePath); res.logSizeBytes = f.length(); } } catch (IOException e) { log.error("error occurred while running job", e); res.logStart = e.getMessage(); res.returnCode = -1; IOUtils.closeQuietly(br); IOUtils.closeQuietly(output); return res; } // Return res.returnCode = p.exitValue(); res.logPath = logFilePath; res.envtUser = System.getProperty("user.name"); try { res.envtServer = InetAddress.getLocalHost().getHostName(); } catch (UnknownHostException e) { res.envtServer = "unknown"; } log.info(String.format("Job ended, RC is %s", res.returnCode)); return res; }
From source file:ca.uqac.info.Job.Launcher.JobLauncher.java
/** * Sets up the ProcessBuilder for the bat file and start it * @return The exitStatus //from www. j a va2 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.modelon.oslc.adapter.fmi.integration.FMUConnector.java
public static FMU loadSingleFMU(String fmuInterfaceCMDPath, String fmuPath, String unzipTempDir) throws IOException { File cmd = new File(fmuInterfaceCMDPath); File fmu = new File(fmuPath); File fmuTempDir = new File(unzipTempDir + File.separator + fmu.getName()); fmuTempDir.mkdirs();/*ww w . j a v a 2s .c o m*/ try { ProcessBuilder builder = new ProcessBuilder(cmd.getPath(), "read", fmu.getPath(), fmuTempDir.getPath()); builder.redirectErrorStream(true); Process p = builder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuilder sbuilder = new StringBuilder(); String aux = ""; while ((aux = reader.readLine()) != null) { aux = aux.replaceAll("\\\\", "\\\\\\\\"); aux += "\r\n"; sbuilder.append(aux); } String json = sbuilder.toString(); ObjectMapper mapper = new ObjectMapper(); mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); FMU fmuObject = mapper.readValue(json, FMU.class); if (fmuObject.fmiVersion != null) return mapper.readValue(json, FMU.class); else return null; } catch (Exception e) { e.printStackTrace(); return null; } }
From source file:nl.tudelft.graphalytics.graphmat.GraphMatPlatform.java
public static void runCommand(String format, String binaryName, List<String> args) throws InterruptedException, IOException { String argsString = ""; for (String arg : args) { argsString += arg + " "; }/* www. j a v a 2s. c om*/ String cmd = String.format(format, binaryName, argsString); LOG.info("running command: {}", cmd); ProcessBuilder pb = new ProcessBuilder(cmd.split(" ")); // pb.redirectErrorStream(true); // pb.redirectError(Redirect.INHERIT); // pb.redirectOutput(Redirect.INHERIT); // pb.inheritIO(); pb.redirectErrorStream(true); Process process = pb.start(); InputStreamReader isr = new InputStreamReader(process.getInputStream()); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } int exit = process.waitFor(); if (exit != 0) { throw new IOException("unexpected error code"); } }
From source file:org.rhq.plugins.jmx.test.JMXPluginTest.java
private static Process startTestServerJvm(String... jvmArgs) throws IOException { String javaHome = System.getProperty("java.home"); String javaCmd = javaHome + "/bin/java"; List<String> args = new ArrayList<String>(); args.add(javaCmd);//from w ww .j a v a2s.co m args.add("-cp"); args.add("target/test-classes"); args.addAll(Arrays.asList(jvmArgs)); args.add(TestProgram.class.getName()); ProcessBuilder processBuilder = new ProcessBuilder(args); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); OutputReader outputReader = new OutputReader(process.getInputStream()); Thread outputReaderThread = new Thread(outputReader); outputReaderThread.setDaemon(true); outputReaderThread.start(); return process; }
From source file:edu.cornell.med.icb.R.RUtils.java
/** * Can be used to start a rserve instance. * @param threadPool The ExecutorService used to start the Rserve process * @param rServeCommand Full path to command used to start Rserve process * @param host Host where the command should be sent * @param port Port number where the command should be sent * @param username Username to send to the server if authentication is required * @param password Password to send to the server if authentication is required * @return The return value from the Rserve instance *//*from ww w . j a v a2 s . c om*/ static Future<Integer> startup(final ExecutorService threadPool, final String rServeCommand, final String host, final int port, final String username, final String password) { if (LOG.isInfoEnabled()) { LOG.info("Attempting to start Rserve on " + host + ":" + port); } return threadPool.submit(new Callable<Integer>() { public Integer call() throws IOException { final List<String> commands = new ArrayList<String>(); // if the host is not local, use ssh to exec the command if (!"localhost".equals(host) && !"127.0.0.1".equals(host) && !InetAddress.getLocalHost().equals(InetAddress.getByName(host))) { commands.add("ssh"); commands.add(host); } // TODO - this will fail when spaces are in the the path to the executable CollectionUtils.addAll(commands, rServeCommand.split(" ")); commands.add("--RS-port"); commands.add(Integer.toString(port)); final String[] command = commands.toArray(new String[commands.size()]); LOG.debug(ArrayUtils.toString(commands)); final ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); final Process process = builder.start(); BufferedReader br = null; try { final InputStream is = process.getInputStream(); final InputStreamReader isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { if (LOG.isDebugEnabled()) { LOG.debug(host + ":" + port + "> " + line); } } process.waitFor(); if (LOG.isInfoEnabled()) { LOG.info("Rserve on " + host + ":" + port + " terminated"); } } catch (InterruptedException e) { LOG.error("Interrupted!", e); process.destroy(); Thread.currentThread().interrupt(); } finally { IOUtils.closeQuietly(br); } final int exitValue = process.exitValue(); if (LOG.isInfoEnabled()) { LOG.info("Rserve on " + host + ":" + port + " returned " + exitValue); } return exitValue; } }); }
From source file:org.zenoss.zep.dao.impl.DaoUtils.java
public static int executeCommand(String command) { String response = ""; ProcessBuilder pb = new ProcessBuilder("bash", "-c", command); pb.redirectErrorStream(true); int shellExitStatus = -1; InputStream shellIn = null;//from w ww . j av a 2 s. c o m try { Process shell = pb.start(); // To capture output from the shell shellIn = shell.getInputStream(); // Wait for the shell to finish and get the return code shellExitStatus = shell.waitFor(); if (shellExitStatus != 0) { response = DaoUtils.convertStreamToStr(shellIn); logger.error("Error (return code: " + shellExitStatus + ") from \"" + command + "\": \nOutput: " + response); } shellIn.close(); } catch (IOException e) { logger.error("Error occured while executing Linux command. Error Description: " + e.getMessage()); } catch (InterruptedException e) { logger.error("Error occured while executing Linux command. Error Description: " + e.getMessage()); } return shellExitStatus; }