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.eclipse.smila.utils.scriptexecution.UnixScriptExecutor.java
/** * {@inheritDoc}//from w w w . j a v a 2 s . c o m */ public int execute(final File file) throws IOException, InterruptedException { final String shell = System.getenv(SHELL_ENV_NAME); if (shell == null || shell.trim().length() == 0) { throw new RuntimeException("Environment variable '" + SHELL_ENV_NAME + "' is not set"); } final ProcessBuilder processBuilder = new ProcessBuilder(shell); processBuilder.directory(file.getParentFile()); processBuilder.redirectErrorStream(true); final Process shellProcess = processBuilder.start(); InputStream inputStream = null; try { inputStream = new FileInputStream(file); final OutputStream shellProcessOutputStream = shellProcess.getOutputStream(); IOUtils.copy(inputStream, shellProcessOutputStream); shellProcessOutputStream.close(); final int retVal = shellProcess.waitFor(); LogHelper.debug(_log, shellProcess.getInputStream()); return retVal; } finally { IOUtils.closeQuietly(inputStream); } }
From source file:org.jenkinsci.plugins.proccleaner.PsBasedHPUXProcessTree.java
@Override public PsBasedProcessTree createProcessTreeFor(String user) throws InterruptedException, IOException { String[] cmd = { "ps", "-u", user, "-f" }; ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); Process proc = pb.start();//from w w w.jav a 2 s. co m final StringWriter writer = new StringWriter(); try { IOUtils.copy(proc.getInputStream(), writer); } catch (IOException e) { LOGGER.warning("'ps' command invocation IOException occurred!"); } BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); if (proc.waitFor() != 0) { LOGGER.warning("'ps' command invocation " + ArrayUtils.toString(cmd) + " failed! Return code: " + proc.exitValue()); LOGGER.fine("Received output from 'ps' command invocation follows:"); if (getLog() != null) { getLog().println("WARNING: 'ps' command invocation " + ArrayUtils.toString(cmd) + " failed! Return code: " + proc.exitValue()); getLog().println("DEBUG: Received output from 'ps' command invocation follows:"); } String line; while ((line = reader.readLine()) != null) { LOGGER.fine(line); if (getLog() != null) getLog().println("DEBUG: '" + line + "'"); } return null; } String line = reader.readLine(); // first line should be "UID PID PPID C STIME TTY TIME COMMAND" - skip it if (StringUtils.isEmpty(line)) { LOGGER.fine("Unrecognized output from 'ps' command invocation! Output is empty!"); if (getLog() != null) { getLog().println("DEBUG: Unrecognized output from 'ps' command invocation! Output is empty!"); } return null; } if (!line.matches("^\\s*UID\\s*PID\\s*PPID\\s*C\\s*STIME\\s*TTY\\s*TIME\\s*COMMAND\\s*$")) { LOGGER.fine("Unrecognized first output line from 'ps' command invocation! Was: '" + line + "'"); if (getLog() != null) { getLog().println( "DEBUG: Unrecognized first output line from 'ps' command invocation! Was: '" + line + "'"); } return null; } PsBasedProcessTree ptree = new PsBasedHPUXProcessTree(); while ((line = reader.readLine()) != null) { String[] ps = line.trim().split(" +", 8); if (ps.length < 8) { LOGGER.fine("Unrecognized output line from 'ps' command invocation! Was: '" + line + "'"); if (getLog() != null) { getLog().println( "DEBUG: Unrecognized output line from 'ps' command invocation! Was '" + line + "'"); } return null; } if (getLog() != null) getLog().println("DEBUG: '" + line + "'"); ptree.addProcess(ps[1] + ' ' + ps[2] + ' ' + ps[7]); } ptree.setLog(getLog()); return ptree; }
From source file:edu.stanford.epad.epadws.dcm4chee.Dcm4CheeOperations.java
public static boolean dcmsnd(File inputDirFile, boolean throwException) throws Exception { InputStream is = null;// w ww.j a va 2 s. c o m InputStreamReader isr = null; BufferedReader br = null; FileWriter tagFileWriter = null; boolean success = false; try { String aeTitle = EPADConfig.aeTitle; String dicomServerIP = EPADConfig.dicomServerIP; String dicomServerPort = EPADConfig.dicomServerPort; String dicomServerTitleAndPort = aeTitle + "@" + dicomServerIP + ":" + dicomServerPort; dicomServerTitleAndPort = dicomServerTitleAndPort.trim(); String dirPath = inputDirFile.getAbsolutePath(); if (pathContainsSpaces(dirPath)) dirPath = escapeSpacesInDirPath(dirPath); File dir = new File(dirPath); int nbFiles = -1; if (dir != null) { String[] filePaths = dir.list(); if (filePaths != null) nbFiles = filePaths.length; } log.info("./dcmsnd: sending " + nbFiles + " file(s) - command: ./dcmsnd " + dicomServerTitleAndPort + " " + dirPath); String[] command = { "./dcmsnd", dicomServerTitleAndPort, dirPath }; ProcessBuilder processBuilder = new ProcessBuilder(command); String dicomScriptsDir = EPADConfig.getEPADWebServerDICOMScriptsDir() + "bin/"; File script = new File(dicomScriptsDir, "dcmsnd"); if (!script.exists()) dicomScriptsDir = EPADConfig.getEPADWebServerDICOMBinDir(); script = new File(dicomScriptsDir, "dcmsnd"); if (!script.exists()) throw new Exception("No script found:" + script.getAbsolutePath()); // Java 6 - Runtime.getRuntime().exec("chmod u+x "+script.getAbsolutePath()); script.setExecutable(true); processBuilder.directory(new File(dicomScriptsDir)); processBuilder.redirectErrorStream(true); Process process = processBuilder.start(); is = process.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line).append("\n"); log.info("./dcmsend output: " + line); } try { int exitValue = process.waitFor(); log.info("DICOM send exit value is: " + exitValue); if (exitValue == 0) success = true; } catch (InterruptedException e) { log.warning("Didn't send DICOM files in: " + inputDirFile.getAbsolutePath(), e); } String cmdLineOutput = sb.toString(); if (cmdLineOutput.toLowerCase().contains("error")) throw new IllegalStateException("Failed for: " + parseError(cmdLineOutput)); return success; } catch (Exception e) { log.warning("DicomSendTask failed to send DICOM files", e); if (e instanceof IllegalStateException && throwException) { throw e; } if (throwException) { throw new IllegalStateException("DicomSendTask failed to send DICOM files", e); } return success; } catch (OutOfMemoryError oome) { log.warning("DicomSendTask out of memory: ", oome); if (throwException) { throw new IllegalStateException("DicomSendTask out of memory: ", oome); } return success; } finally { IOUtils.closeQuietly(tagFileWriter); IOUtils.closeQuietly(br); IOUtils.closeQuietly(isr); IOUtils.closeQuietly(is); } }
From source file:com.photon.phresco.framework.param.impl.IosDeviceTypeParameterImpl.java
private String cureentXcodeVersion() throws IOException { String version = ""; ProcessBuilder pb = new ProcessBuilder("/bin/sh", "-c", "xcodebuild -version"); pb.redirectErrorStream(true); pb.directory(new File("/")); Process process = pb.start(); InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line;//from w ww . j a va 2 s . c om while ((line = br.readLine()) != null) { String[] splited = line.split("\\s"); version = splited[1]; break; } return version; }
From source file:com.novartis.opensource.yada.plugin.ScriptPreprocessor.java
/** * Enables the execution of a script stored in the {@code YADA_BIN} directory. * To execute a script preprocessor plugin, pass {@code preArgs}, or just {@code args} * the first argument being the name of the script executable, and the rest of the arguments * those, in order, to pass to it. If {@link YADARequest#getPreArgs()} is not null * and {@link YADARequest#getPlugin()} is null, then the plugin will be set to * {@link YADARequest#SCRIPT_PREPROCESSOR} automatically. * <p>/* w w w. j av a 2 s . c om*/ * The script must return a JSON object with name/value pairs corresponding * to {@link YADARequest} parameters. These name/value pairs are then marshaled into * {@code yadaReq}, which is subsequently returned by the method. * </p> * @see com.novartis.opensource.yada.plugin.Bypass#engage(com.novartis.opensource.yada.YADARequest) */ @Override public YADARequest engage(YADARequest yadaReq) throws YADAPluginException { List<String> cmds = new ArrayList<>(); // get args List<String> args = yadaReq.getPreArgs().size() == 0 ? yadaReq.getArgs() : yadaReq.getPreArgs(); // add plugin try { cmds.add(Finder.getEnv("yada_bin") + args.remove(0)); } catch (YADAResourceException e) { String msg = "There was a problem locating the resource or variable identified by the supplied JNDI path (yada_bin) in the initial context."; throw new YADAPluginException(msg, e); } // add args cmds.addAll(args); for (String arg : args) { cmds.add(arg); } // add yadaReq json cmds.add(yadaReq.toString()); l.debug("Executing script plugin: " + cmds); String scriptResult = ""; String s = null; try { ProcessBuilder builder = new ProcessBuilder(cmds); builder.redirectErrorStream(true); Process process = builder.start(); try (BufferedReader si = new BufferedReader(new InputStreamReader(process.getInputStream()))) { while ((s = si.readLine()) != null) { l.debug(" LINE: " + s); scriptResult += s; } } process.waitFor(); JSONObject params = new JSONObject(scriptResult); for (String param : JSONObject.getNames(params)) { JSONArray ja = (JSONArray) params.get(param); l.debug("JSON array " + ja.toString()); // remove square brackets and leading/trailing quotes String values = ja.toString().substring(2, ja.toString().length() - 2); // remove "," between values and stuff in array String[] value = values.split("\",\""); l.debug("Value has " + value.length + " elements"); yadaReq.invokeSetter(param, value); } } catch (IOException e) { String msg = "Failed to get input from InputStream."; throw new YADAPluginException(msg, e); } catch (InterruptedException e) { String msg = "The external process executing the script was interrupted."; throw new YADAPluginException(msg, e); } catch (JSONException e) { String msg = "Parameter configuration failed. The script return value should conform to the syntax:\n"; msg += " {\"key\":[\"value\"...],...}.\n"; msg += " The array syntax for values complies to the return value of HTTPServletResponse.getParameterMap().toString()"; throw new YADAPluginException(msg, e); } catch (YADARequestException e) { String msg = "Unable to set parameters."; throw new YADAPluginException(msg, e); } return yadaReq; }
From source file:ape.ContinueNodeCommand.java
public boolean runImpl(String[] args) throws IOException { String nodeType = null;//from w ww. j a v a2 s . co m nodeType = args[0]; if (Main.VERBOSE) System.out.println("Nodetype" + args[0]); Process p; if (nodeType.toLowerCase().equals("datanode") || nodeType.toLowerCase().equals("tasktracker") || nodeType.toLowerCase().equals("jobtracker") || nodeType.toLowerCase().equals("namenode")) { System.out.println("Suspend is about to execute the following command:"); String cmd = "echo \"kill -18 \\$(ps aux | grep -i " + nodeType + " | grep -v grep | grep -v ape | awk -F ' ' '{print \\$2}')\" > kill-node.sh && chmod +x kill-node.sh && ./kill-node.sh"; System.out.println(cmd); /** * The above code block checks to see if a valid node type is passed. * If it is, then it sends a very ugly bash command to kill the corresponding process. * It gets a list of running processes, then greps it for the node type, then * removes the result generated by running grep, then it gets the process ID of that line * */ ProcessBuilder pb = new ProcessBuilder("bash", "-c", cmd); pb.redirectErrorStream(true); Process sh; try { sh = pb.start(); } catch (IOException e1) { e1.printStackTrace(); Main.logger.info(e1); return false; } try { sh.waitFor(); } catch (InterruptedException e) { System.out.println("The suspend node command caught an interrupt"); e.printStackTrace(); Main.logger.info("The suspend command caught an interrupt"); Main.logger.info(e); return false; } InputStream shIn = sh.getInputStream(); int c; while ((c = shIn.read()) != -1) { System.out.write(c); } try { shIn.close(); } catch (IOException e) { System.out.println("Could not close InputStream from the suspend process."); e.printStackTrace(); Main.logger.info("Could not close InputStream from the suspend process."); Main.logger.info(e); return false; } return true; } else { System.err.println("Invalid node type."); return false; } }
From source file:frk.gpssimulator.service.impl.DefaultGpsdService.java
/** * Start given process.//from w w w . j a v a 2 s .co m * @param command * @param wait for process to exit * @return */ int startProc(String command, Boolean wait) throws IOException, InterruptedException { String[] commandArray = command.split(" "); ProcessBuilder pb = new ProcessBuilder(commandArray); pb.redirectErrorStream(true); //redirect errorstream and outputstream to single stream Process proc = pb.start(); BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); String line; //empty the output buff of the proc while ((line = in.readLine()) != null) { LOGGER.info(line); } if (wait) { return proc.waitFor(); } else { return 0; } }
From source file:com.jbrisbin.vpc.jobsched.exe.ExeMessageHandler.java
public ExeMessage handleMessage(final ExeMessage msg) throws Exception { log.debug("handling message: " + msg.toString()); List<String> args = msg.getArgs(); args.add(0, msg.getExe());/* w ww . j av a 2s . c om*/ try { ProcessBuilder pb = new ProcessBuilder(args); pb.environment().putAll(msg.getEnv()); pb.directory(new File(msg.getDir())); pb.redirectErrorStream(true); Process p = pb.start(); BufferedInputStream stdout = new BufferedInputStream(p.getInputStream()); byte[] buff = new byte[4096]; for (int bytesRead = 0; bytesRead > -1; bytesRead = stdout.read(buff)) { msg.getOut().write(buff, 0, bytesRead); } p.waitFor(); } catch (Throwable t) { log.error(t.getMessage(), t); Object errmsg = t.getMessage(); if (null != errmsg) { msg.getOut().write(((String) errmsg).getBytes()); } } return msg; }
From source file:com.googlecode.flyway.maven.largetest.MavenLargeTest.java
/** * Runs Maven in this directory with these extra arguments. * * @param expectedReturnCode The expected return code for this invocation. * @param dir The directory below src/test/resources to run maven in. * @param extraArgs The extra arguments (if any) for Maven. * @return The standard output.//w w w .j a v a 2 s. c o m * @throws Exception When the execution failed. */ private String runMaven(int expectedReturnCode, String dir, String... extraArgs) throws Exception { String m2Home = System.getenv("M2_HOME"); String flywayVersion = System.getProperty("flywayVersion"); String extension = ""; if (System.getProperty("os.name").startsWith("Windows")) { extension = ".bat"; } List<String> args = new ArrayList<String>(); args.add(m2Home + "/bin/mvn" + extension); args.add("-Dflyway.version=" + flywayVersion); args.addAll(Arrays.asList(extraArgs)); ProcessBuilder builder = new ProcessBuilder(args); builder.directory(new File(installDir + "/" + dir)); builder.redirectErrorStream(true); Process process = builder.start(); String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8")); int returnCode = process.waitFor(); System.out.print(stdOut); assertEquals("Unexpected return code", expectedReturnCode, returnCode); return stdOut; }
From source file:com.googlecode.flyway.ant.AntLargeTest.java
/** * Runs Ant in this directory with these extra arguments. * * @param expectedReturnCode The expected return code for this invocation. * @param dir The directory below src/test/resources to run maven in. * @param extraArgs The extra arguments (if any) for Maven. * @return The standard output.// w ww .j a v a 2 s . c o m * @throws Exception When the execution failed. */ private String runAnt(int expectedReturnCode, String dir, String... extraArgs) throws Exception { String antHome = System.getenv("ANT_HOME"); String extension = ""; if (System.getProperty("os.name").startsWith("Windows")) { extension = ".bat"; } List<String> args = new ArrayList<String>(); args.add(antHome + "/bin/ant" + extension); args.add("-DlibDir=" + System.getProperty("libDir")); args.addAll(Arrays.asList(extraArgs)); ProcessBuilder builder = new ProcessBuilder(args); builder.directory(new File(installDir + "/" + dir)); builder.redirectErrorStream(true); Process process = builder.start(); String stdOut = FileCopyUtils.copyToString(new InputStreamReader(process.getInputStream(), "UTF-8")); int returnCode = process.waitFor(); System.out.print(stdOut); assertEquals("Unexpected return code", expectedReturnCode, returnCode); return stdOut; }