@Override public void execute() throws LifecycleException { Process process = null; try { List<String> command = new ShutdownAdminServerCommand().getCommand(); ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); process = builder.start(); Thread consoleConsumer = new Thread(new ConsoleConsumer(process, configuration.isOutputToConsole())); consoleConsumer.setDaemon(true); consoleConsumer.start(); while (isServerRunning()) { try { Thread.sleep(500L); } catch (InterruptedException e) { logger.log(Level.INFO, "Container shutdown interrupted"); throw e; } } logger.log(Level.INFO, "Stopped WebLogic Server."); return; } catch (Exception ex) { throw new LifecycleException("Container shutdown failed.", ex); } }
protected Process startProcess(@NotNull List<String> commands) throws IOException { ProcessBuilder builder = new ProcessBuilder(commands); setupEnvironment(builder.environment()); builder.directory(myWorkDirectory); builder.redirectErrorStream(myRedirectErrorStream); return builder.start(); }
/** Run new Maven os process with given arguments and commands. */ public void execute() { Process process = null; BufferedReader br = null; try { ProcessBuilder processBuilder = getProcessBuilder(); processBuilder.redirectErrorStream(true); log.info("Starting process: " + processBuilder.command()); process = processBuilder.start(); // Read output br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = br.readLine()) != null) { System.out.println(line); } process.waitFor(); } catch (Exception e) { throw new RuntimeException(e); } finally { close(br); destroyProcess(process); } }
public void runCommand(String envName, String envValue, String... command) { try { ProcessBuilder pb = new ProcessBuilder(command); Map<String, String> env = pb.environment(); env.put(envName, envValue); // env.put(/*"BIRT_HOME"*/envName, // envValue/*"/home/alexander/myItemsLast/birt-runtime-4_4_1/"*/); pb.redirectErrorStream(true); Process p = pb.start(); InputStream is = p.getInputStream(); String pbMessage = "\nCommand " + Arrays.asList(command) + " reported"; System.out.println(pbMessage); log.write(pbMessage); int b; while ((b = is.read()) >= 0) System.out.write(b); is.close(); p.destroy(); } catch (IOException e) { String pbMessage = "\nCommand " + Arrays.asList(command) + " reported " + e; System.err.println(pbMessage); log.write(pbMessage); } }
/** * Return bursts from a hexa frame without time advance * * @param hexaFrame frame in hexadecimal * @param fn the frame number * @param siType the System Information type (5/5ter/6) * @return String[] with all 4 bursts from the frame * @throws IOException if error while executing command */ public static String[] getBursts(String hexaFrame, String fn, String siType) throws IOException { String[] bursts = new String[6]; bursts[4] = fn; bursts[5] = siType; int i = 0; // delete Time Advance StringBuilder hexaFrameNoTA = new StringBuilder(hexaFrame); hexaFrameNoTA.setCharAt(2, '0'); hexaFrameNoTA.setCharAt(3, '0'); ProcessBuilder pb = new ProcessBuilder("./gsmframecoder", hexaFrameNoTA.toString()); pb.redirectErrorStream(true); pb.directory(Configuration.gsmFrameCoder); Process p = pb.start(); p.getOutputStream().flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String ligne = new String(); while ((ligne = reader.readLine()) != null) { if (ligne.length() == 114 && i < 4) { bursts[i] = ligne; i++; } } p.destroy(); p.destroyForcibly(); return bursts; }
public void startProfile(FirefoxProfile profile, File profileDir, String... commandLineFlags) throws IOException { String profileAbsPath = profileDir.getAbsolutePath(); setEnvironmentProperty("XRE_PROFILE_PATH", profileAbsPath); setEnvironmentProperty("MOZ_NO_REMOTE", "1"); setEnvironmentProperty("MOZ_CRASHREPORTER_DISABLE", "1"); // Disable Breakpad setEnvironmentProperty( "NO_EM_RESTART", "1"); // Prevent the binary from detaching from the console if (isOnLinux() && (profile.enableNativeEvents() || profile.alwaysLoadNoFocusLib())) { modifyLinkLibraryPath(profileDir); } List<String> commands = new ArrayList<String>(); commands.add(getExecutable().getPath()); commands.addAll(Arrays.asList(commandLineFlags)); ProcessBuilder builder = new ProcessBuilder(commands); builder.redirectErrorStream(true); builder.environment().putAll(getExtraEnv()); getExecutable().setLibraryPath(builder, getExtraEnv()); if (stream == null) { stream = getExecutable().getDefaultOutputStream(); } startFirefoxProcess(builder); copeWithTheStrangenessOfTheMac(builder); startOutputWatcher(); }
public Process createProcess() throws ExecutionException { if (LOG.isDebugEnabled()) { LOG.debug("Executing [" + getCommandLineString() + "]"); } List<String> commands; try { checkWorkingDirectory(); if (StringUtil.isEmptyOrSpaces(myExePath)) { throw new ExecutionException( IdeBundle.message("run.configuration.error.executable.not.specified")); } commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList()); } catch (ExecutionException e) { LOG.warn(e); throw e; } try { ProcessBuilder builder = new ProcessBuilder(commands); setupEnvironment(builder.environment()); builder.directory(myWorkDirectory); builder.redirectErrorStream(myRedirectErrorStream); return builder.start(); } catch (IOException e) { LOG.warn(e); throw new ProcessNotCreatedException(e.getMessage(), e, this); } }
private static String readProcessOutput(String command, String arguments) { String result = ""; ProcessBuilder pb = new ProcessBuilder(command, arguments); pb.redirectErrorStream(true); try { Process process = pb.start(); InputStream stdout = process.getInputStream(); final BufferedReader brstdout = new BufferedReader(new InputStreamReader(stdout)); String line = null; try { StringBuilder stringBuilder = new StringBuilder(); while ((line = brstdout.readLine()) != null) { stringBuilder.append(line); } result = stringBuilder.toString(); } catch (Exception e) { } finally { IOUtils.closeQuietly(brstdout); IOUtils.closeQuietly(stdout); } } catch (Throwable e) { e.printStackTrace(); } return result; }
protected void runPub( IContainer container, final MessageConsole console, List<String> args, boolean wait) { stringBuilder = new StringBuilder(); ProcessBuilder builder = new ProcessBuilder(); builder.directory(container.getLocation().toFile()); builder.redirectErrorStream(true); builder.command(args); final Process process; try { process = builder.start(); final Thread stdoutThread = new Thread( new Runnable() { @Override public void run() { try { copy(process.getInputStream(), console); } catch (IOException e) { // do nothing } } }); stdoutThread.start(); if (wait) { process.waitFor(); } } catch (IOException e) { String message = NLS.bind(PubMessages.RunPubJob_failed, command, e.toString()); console.println(message); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
/** * Method description * * @return * @throws IOException */ protected Process createProcess() throws IOException { if (logger.isDebugEnabled()) { StringBuilder cmd = new StringBuilder(); for (String c : command) { cmd.append(c).append(" "); } logger.debug("start external process '{}'", cmd.toString()); } ProcessBuilder processBuilder = new ProcessBuilder(command); if (workDirectory != null) { processBuilder = processBuilder.directory(workDirectory); } Map<String, String> env = processBuilder.environment(); if (useSystemEnvironment) { env.putAll(System.getenv()); } if (environment != null) { env.putAll(environment); } return processBuilder.redirectErrorStream(true).start(); }
public static String test123() { String r = ""; try { // System.setSecurityManager(null); // String[] callArgs = {"mkdir", "/home/alexis/test123"}; String[] callArgs = {"ls"}; ProcessBuilder pb = new ProcessBuilder(callArgs); pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(); // BufferedReader br = new BufferedReader(new InputStreamReader(p.getErrorStream() )); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = ""; System.out.println("Start Output"); while ((line = br.readLine()) != null) r += line + "\n"; System.out.println("End Output"); /*Process p = Runtime.getRuntime().exec(callArgs); p.waitFor(); System.out.println("Test Complete");*/ r = line; } catch (IOException e) { System.out.println(e); r = "Test failed"; } catch (Exception e) { } return r; }
private void execute(List<String> command2) { try { ProcessBuilder builder = new ProcessBuilder(command2); if (env.size() > 0) builder.environment().putAll(env); if (StringUtils.hasLength(workingDir)) builder.directory(new File(workingDir)); builder.redirectErrorStream(true); process = builder.start(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); try { String line; while ((line = stdInput.readLine()) != null) { System.out.println(line); } process.waitFor(); } finally { stdInput.close(); } } catch (IOException e) { throw new AssertionError(e); } catch (InterruptedException e) { throw new AssertionError(e); } }
private String getIPAndroid() { String host = "localhost"; try { ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "adb shell netcfg"); builder.redirectErrorStream(true); Process p = builder.start(); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while (true) { line = r.readLine(); if (line == null) { break; } if (line.contains("0x00001043")) { // wlan0 UP 192.168.1.79/24 // 0x00001043 b4:52:7d:c5:8b:69 int index = line.indexOf("/24"); line = line.substring(0, index); index = line.lastIndexOf(" "); host = line.substring(index + 1); break; } } } catch (IOException e) { e.printStackTrace(); Notifications.Bus.notify( new Notification( Constant.GROUND_ID, "Error getIPAndroid", e.toString(), NotificationType.ERROR)); } return host; }
/** * This method runs the ProcessBuilder and waits for it to finish. At the end it checks the return * state from the process and if it is a failure it prints the last line of the console output. * * @param builder */ private void bashProcess(ProcessBuilder builder) { Process process = null; builder.redirectErrorStream(true); try { process = builder.start(); } catch (IOException e1) { e1.printStackTrace(); } InputStream stdout = process.getInputStream(); BufferedReader stdoutBuffered = new BufferedReader(new InputStreamReader(stdout)); String line = null; String last = null; try { while ((line = stdoutBuffered.readLine()) != null) { last = line; if (isCancelled()) { process.destroy(); return; } } } catch (IOException e1) { e1.printStackTrace(); } try { if (process.waitFor() != 0) { firePropertyChange("failure", null, last); errorState = true; } } catch (InterruptedException e1) { e1.printStackTrace(); } }
@Before public void setUp() throws Exception { FileUtils.deleteDirectory(SVN_DIR); System.out.println("setup..."); SVN_DIR.mkdirs(); ProcessBuilder builder = new ProcessBuilder(SVNADMIN_EXEC, "create", SVN_DIR.getAbsolutePath()); builder.redirectErrorStream(true); Process process = builder.start(); process.waitFor(); FileUtils.writeStringToFile( new File(SVN_DIR, "conf/svnserve.conf"), "[general]\npassword-db = passwd", null); FileUtils.writeStringToFile(new File(SVN_DIR, "conf/passwd"), "[users]\nguest = guest", null); System.out.println("setup ok."); writer = context.mock(LrdWriter.class); repositoryBean = new RepositoryBean(); repositoryBean.setUrl(SVN_URL); repositoryBean.setUserName(SVN_USER); repositoryBean.setPassword(SVN_PASS); }
private static void checkIsAvailableAndGetVersion() { ProcessBuilder pb = new ProcessBuilder(COMMAND, "--version"); pb.redirectErrorStream(true); Process p = null; try { p = pb.start(); p.waitFor(); perconaToolkitVersion = StreamUtil.getStreamContents(p.getInputStream()); if (perconaToolkitVersion != null) { perconaToolkitVersion = perconaToolkitVersion.replaceAll("\n|\r", ""); } available = true; log.info("Using percona toolkit: " + perconaToolkitVersion); } catch (IOException e) { available = false; } catch (InterruptedException e) { available = false; } finally { if (p != null) { StreamUtil.closeQuietly(p.getErrorStream()); StreamUtil.closeQuietly(p.getInputStream()); StreamUtil.closeQuietly(p.getOutputStream()); p.destroy(); } } }
protected ProtocolMetaData doDeploy(Archive<?> archive) throws DeploymentException { List<String> command = new ArrayList<>(); command.add("gcloud"); if (configuration.isDebug()) { command.add("--verbosity"); command.add("debug"); } command.add("preview"); command.add("app"); command.add("run"); command.add(getAppLocation().getPath()); log.info("GCloud command: " + command); try { DockerContainer.removeAll(); } catch (Exception e) { throw new DeploymentException("Cannot remove all previous Docker containers.", e); } ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); try { process = builder.start(); } catch (IOException e) { throw new IllegalStateException("Error running gcloud!", e); } Thread streamThread = new Thread( new Runnable() { public void run() { try { try (InputStream ps = process.getInputStream()) { int x; while ((x = ps.read()) != -1) { System.out.write(x); } } } catch (IOException ignored) { } } }); streamThread.start(); String host = configuration.getHost(); int port = readPort(); String serverUrl = "http://" + host + ":" + port + "/_ah/health"; try { delayArchiveDeploy( serverUrl, configuration.getStartupTimeout(), 2000L, new GCloudURLChecker()); } catch (Exception e) { throw new DeploymentException("Error delaying archive deployment.", e); } return getProtocolMetaData(host, port, DEFAULT); }
public static void killProcessWindows() { String osname = System.getProperty("os.name"); if (osname.startsWith("Windows")) { Bundle bundlenew = Platform.getBundle("com.eco.bio7"); URL locationUrl = FileLocator.find(bundlenew, new Path("/process/Process.exe"), null); URL url = null; try { url = FileLocator.toFileURL(locationUrl); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } File file = new File(url.getFile()); // Runtime runtime = Runtime.getRuntime(); // String arg = " -k Rserve.exe"; String line; // process = runtime.exec("\""+file.getCanonicalPath()+"\"" + arg); List<String> args = new ArrayList<String>(); try { args.add(file.getCanonicalPath()); } catch (IOException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } args.add("-k"); args.add("Rserve.exe"); ProcessBuilder pb = new ProcessBuilder(args); pb.redirectErrorStream(); try { process = pb.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); try { while ((line = input.readLine()) != null) {} } catch (IOException e) { e.printStackTrace(); } try { input.close(); } catch (IOException e) { e.printStackTrace(); } process.destroy(); } }
protected void downloadApacheFelixWebManagement(final String repoId) throws IOException, Exception, MalformedURLException { FileUtils.deleteDirectory(new File(FELIX_HOME, "felix-cache")); final ScheduledServicePropertyResource prop = new ScheduledServicePropertyResource(); prop.setKey("repositoryId"); prop.setValue(repoId); TaskScheduleUtil.runTask("PublishObrDescriptorTask", prop); downloadFile( new URL(getRepositoryUrl(repoId) + ".meta/obr.xml"), "target/" + getTestId() + "/download/obr.xml"); final ProcessBuilder pb = new ProcessBuilder( "java", "-Dfelix.config.properties=" + FELIX_CONF.toURI(), "-jar", "bin/felix.jar"); pb.directory(FELIX_HOME); pb.redirectErrorStream(true); final Process p = pb.start(); final Object lock = new Object(); final Thread t = new Thread( new Runnable() { public void run() { // just a safeguard, if felix get stuck kill everything try { synchronized (lock) { lock.wait(5 * 1000 * 60); } } catch (final InterruptedException e) { // ignore } p.destroy(); } }); t.setDaemon(true); t.start(); synchronized (lock) { final InputStream input = p.getInputStream(); final OutputStream output = p.getOutputStream(); waitFor(input, "g!"); output.write(("obr:repos add " + getRepositoryUrl(repoId) + ".meta/obr.xml\r\n").getBytes()); output.flush(); waitFor(input, "g!"); output.write("obr:deploy -s org.apache.felix.webconsole\r\n".getBytes()); output.flush(); waitFor(input, "done."); p.destroy(); lock.notifyAll(); } }
protected static CommandResult executeCommand( List<String> commands, List<String> stdins, long timeout) throws IOException { // Process開始 ProcessBuilder builder = new ProcessBuilder(commands); builder.redirectErrorStream(true); Process process = builder.start(); // WatchDogタイマー実行 WatchDog watchDog = new WatchDog(process, timeout); Thread thread = new Thread(watchDog); thread.start(); // 標準入力へ書き込み if (stdins != null && stdins.size() > 0) { OutputStream out = process.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); for (String stdin : stdins) { writer.write(stdin); writer.newLine(); } closeQuietly(writer); closeQuietly(out); } // プロセス終了まで待機 try { process.waitFor(); thread.interrupt(); } catch (InterruptedException ignore) { } // タイムアウト発生時 if (watchDog.isTimeout) { AutoException exception = new AutoException("ECOMMON-000301", commands); exception.addDetailInfo("stdins=" + stdins); throw exception; } // 標準出力の読み込み InputStream in = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); List<String> stdouts = new ArrayList<String>(); String line; while ((line = reader.readLine()) != null) { stdouts.add(line); } closeQuietly(reader); closeQuietly(in); // 実行結果 CommandResult result = new CommandResult(); result.setExitValue(process.exitValue()); result.setStdouts(stdouts); return result; }
/** * Start a process Start a process and merge its error and output streams * * @see ExecHelper#exec() */ public static ExecHelper execMerge( IExecEvents handler, String command[], Map<String, String> envp, File dir) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(dir); processBuilder.redirectErrorStream(true); if (envp != null) processBuilder.environment().putAll(envp); return new ExecHelper(handler, processBuilder.start()); }
public void start() throws Exception { ProcessBuilder builder = new ProcessBuilder(KTBS_COMMAND, "-4"); builder.redirectErrorStream(true); ktbsProcess = builder.start(); Runtime.getRuntime().addShutdownHook(shutdownHook); displayOutput.start(); checkServerStarted.start(); checkServerStarted.join(); }
public ProcessManager(String[] c, String[] env) throws IOException { String[] cx = c; String pnam = "this is a test"; String tcmd = Utils.join(cx, " "); if (isWindows) { cx = new String[] {"cmd", "/c", tcmd}; } else { cx = new String[] {"/usr/bin/ruby", "-e", rbProg.replaceAll("@@@", Utils.join(c, " "))}; } this.cmd = cx; ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); pb.environment().put("the_command", tcmd); pb.environment().put("the_title", pnam); if (env != null) { for (String e : env) { int ee = e.indexOf("="); if (ee > 0) pb.environment().put(e.substring(0, ee), e.substring(ee + 1)); else pb.environment().put(e, ""); } } proc = pb.start(); lk = new Semaphore(0); scribe = new Scribe(); scribe_thread = new Thread(scribe); scribe_thread.start(); new Thread( new Runnable() { public void run() { try { proc.waitFor(); processes.remove(ProcessManager.this.keyHandle()); System.err.println("process " + proc.toString() + " died"); ProcessManager.this.processDied(); } catch (InterruptedException ignore) { } } }) .start(); /* if (isWindows) { proc.getOutputStream().write("title this is a test\n%the_command%\n".getBytes()); proc.getOutputStream().flush(); proc.getOutputStream().close(); } */ try { scribe_thread.join(333); } catch (InterruptedException ignore) { } // wait for one third of a second processes.put(keyHandle(), this); }
/** * Actually executes pt-online-schema change. Does not generate any Sql. * * @return always <code>null</code> */ @Override public Sql[] generate(Database database) { List<String> cmndline = buildCommand(database); log.info("Executing: " + filterCommands(cmndline)); ProcessBuilder pb = new ProcessBuilder(cmndline); pb.redirectErrorStream(true); Process p = null; final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final OutputStream tee = new FilterOutputStream(outputStream) { @Override public void write(int b) throws IOException { if (b == '\n') { log.info(outputStream.toString(Charset.defaultCharset().toString())); outputStream.reset(); } else { super.write(b); } } }; try { p = pb.start(); final InputStream in = p.getInputStream(); final InputStream err = p.getErrorStream(); IOThread reader = new IOThread(in, tee); IOThread reader2 = new IOThread(err, tee); reader.start(); reader2.start(); int exitCode = p.waitFor(); reader.join(5000); reader2.join(5000); // log the remaining output log.info(outputStream.toString(Charset.defaultCharset().toString())); if (exitCode != 0) { throw new RuntimeException("Percona exited with " + exitCode); } } catch (IOException e) { throw new UnexpectedLiquibaseException(e); } catch (InterruptedException e) { throw new UnexpectedLiquibaseException(e); } finally { if (p != null) { StreamUtil.closeQuietly(p.getErrorStream()); StreamUtil.closeQuietly(p.getInputStream()); StreamUtil.closeQuietly(p.getOutputStream()); p.destroy(); } StreamUtil.closeQuietly(outputStream); } return null; }
/** runs "kill -9" on the specified pid */ public static void kill9(Integer pid) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder("kill", "-9", pid.toString()); pb.redirectErrorStream(); Process p = pb.start(); int code = p.waitFor(); if (code != 0) { String output = IOUtils.readFully(p.getInputStream()); throw new RuntimeException("kill return code " + code + ": " + output); } }
private static void readOutputAndError() throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder("ps"); pb.redirectErrorStream(true); Process process = pb.start(); InputStream stdout = process.getInputStream(); Charset cs = StandardCharsets.UTF_8; String output = IOUtils.toString(stdout, cs); System.out.println(output); process.waitFor(); }
/** * Launch the specified call list. * * @param callList launch the call list * @return {@code true} in case the launch was successful */ private boolean launchCallList(final List<String> callList) { try { final ProcessBuilder pBuilder = new ProcessBuilder(callList); File workingDirectory = DirectoryManager.getInstance().getWorkingDirectory(); if (workingDirectory != null) { pBuilder.directory(workingDirectory); } pBuilder.redirectErrorStream(true); final Process proc = pBuilder.start(); proc.getOutputStream().close(); final StringBuilder outputBuffer = new StringBuilder(); outputReader = new BufferedReader(new InputStreamReader(proc.getInputStream())); launchTimer.start(); cancelExecution = false; while (true) { if (cancelExecution) { throw new IOException("Response Timeout."); } final String line = outputReader.readLine(); if (line == null) { errorData = outputBuffer.toString().trim(); return false; } if (line.endsWith("Startup done.")) { outputReader.close(); return true; } outputBuffer.append(line); outputBuffer.append('\n'); } } catch (@Nonnull final Exception e) { final StringWriter sWriter = new StringWriter(); final PrintWriter writer = new PrintWriter(sWriter); e.printStackTrace(writer); writer.flush(); errorData = sWriter.toString(); return false; } finally { if (outputReader != null) { try { outputReader.close(); } catch (@Nonnull final IOException e) { // nothing } } outputReader = null; } }
static String run(String... cmd) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder(cmd); pb.redirectErrorStream(true); Process p = pb.start(); InputStreamReader reader = new InputStreamReader(p.getInputStream()); StringWriter sw = new StringWriter(); char[] chars = new char[512]; for (int len; (len = reader.read(chars)) > 0; ) sw.write(chars, 0, len); int exitValue = p.waitFor(); if (exitValue != 0) sw.write("\nexit=" + exitValue); p.destroy(); return sw.toString(); }
@Override public void kill(int pid) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder("taskkill", "/F", "/PID", Integer.toString(pid)); pb.redirectErrorStream(true); Process p = pb.start(); // Read output to avoid deadlock Reader r = new InputStreamReader(p.getInputStream()); BufferedReader br = new BufferedReader(r); for (String line = br.readLine(); line != null; line = br.readLine()) {} p.waitFor(); }
private static String run(String... cmds) throws IOException { ProcessBuilder pb = new ProcessBuilder(cmds); pb.redirectErrorStream(true); Process process = pb.start(); StringWriter sw = new StringWriter(); char[] chars = new char[1024]; try (Reader r = new InputStreamReader(process.getInputStream())) { for (int len; (len = r.read(chars)) > 0; ) { sw.write(chars, 0, len); } } return sw.toString(); }