List of usage examples for java.lang Process getInputStream
public abstract InputStream getInputStream();
From source file:com.samczsun.helios.Helios.java
private static boolean ensurePython2Set0(boolean forceCheck) { String python2Location = Settings.PYTHON2_LOCATION.get().asString(); if (python2Location.isEmpty()) { SWTUtil.showMessage("You need to set the location of the Python/PyPy 2.x executable", true); setLocationOf(Settings.PYTHON2_LOCATION); python2Location = Settings.PYTHON2_LOCATION.get().asString(); }//from w ww .j a v a 2 s .c o m if (python2Location.isEmpty()) { return false; } if (python2Verified == null || forceCheck) { try { Process process = new ProcessBuilder(python2Location, "-V").start(); String result = IOUtils.toString(process.getInputStream()); String error = IOUtils.toString(process.getErrorStream()); python2Verified = error.startsWith("Python 2") || result.startsWith("Python 2"); } catch (Throwable t) { StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); SWTUtil.showMessage("The Python 2.x executable is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString()); t.printStackTrace(); python2Verified = false; } } return python2Verified; }
From source file:net.ftb.util.OSUtils.java
/** * Used to check if a posix OS is 64-bit * @return true if 64-bit Posix OS//ww w . ja va 2 s .co m */ public static boolean is64BitPosix() { String line, result = ""; try { Process command = Runtime.getRuntime().exec("uname -m"); BufferedReader in = new BufferedReader(new InputStreamReader(command.getInputStream())); while ((line = in.readLine()) != null) { result += (line + "\n"); } } catch (Exception e) { Logger.logError("Posix bitness check failed", e); } // 32-bit Intel Linuces, it returns i[3-6]86. For 64-bit Intel, it says x86_64 return result.contains("_64"); }
From source file:hoot.services.command.CommandRunner.java
private static int handleProcessStatic(Process pProcess, String pOrigCmd, Writer pOut, Writer pErr, List<CharPump> stdOutErrList, MutableBoolean interrupt) throws IOException, InterruptedException { CharPump outpump = new CharPump(new BufferedReader(new InputStreamReader(pProcess.getInputStream())), pOut, pOrigCmd, interrupt);/* w w w . j a v a 2 s.c o m*/ stdOutErrList.add(outpump); CharPump errpump = new CharPump(new BufferedReader(new InputStreamReader(pProcess.getErrorStream())), pErr, pOrigCmd, interrupt); stdOutErrList.add(errpump); outpump.start(); errpump.start(); outpump.join(); errpump.join(); if (_log.isInfoEnabled()) _log.info("Waiting for '" + pOrigCmd + "' to complete."); int status = pProcess.waitFor(); return status; }
From source file:com.alibaba.otter.shared.common.utils.cmd.Exec.java
public static Result execute(Process process, String cmd, String outputLog, byte[] input, File workingDir) throws Exception { // ???// w ww . j av a 2 s . c o m Thread inputThread = new InputPumper((input == null) ? new byte[] {} : input, process.getOutputStream()); StreamCollector stderr = null; StreamCollector stdout = null; FileOutputStream fileOutput = null; StreamAppender outputLogger = null; String errString = null; String outString = null; try { if (outputLog == null) { stdout = new StreamCollector(process.getInputStream()); stderr = new StreamCollector(process.getErrorStream()); stdout.start(); stderr.start(); } else { errString = "stderr output redirected to file " + outputLog; outString = "stdout output redirected to file " + outputLog; fileOutput = new FileOutputStream(outputLog); outputLogger = new StreamAppender(fileOutput); outputLogger.writeInput(process.getErrorStream(), process.getInputStream()); } inputThread.start(); final int exitCode = process.waitFor(); inputThread.join(); if (outputLogger != null) { outputLogger.finish(); } if (stdout != null) { stdout.join(); outString = stdout.toString(); } if (stderr != null) { stderr.join(); errString = stderr.toString(); } return new Result(cmd.toString(), outString, errString, exitCode); } finally { IOUtils.closeQuietly(fileOutput); if (process != null) { // evitons http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6462165 process.getInputStream().close(); process.getOutputStream().close(); process.getErrorStream().close(); process.destroy(); } } }
From source file:com.evolveum.midpoint.test.util.TestUtil.java
public static String execSystemCommand(String command, boolean ignoreExitCode) throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); LOGGER.debug("Executing system command: {}", command); Process process = runtime.exec(command); int exitCode = process.waitFor(); LOGGER.debug("Command exit code: {}", exitCode); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder output = new StringBuilder(); String line = null;// www . jav a 2 s .c o m while ((line = reader.readLine()) != null) { output.append(line); } reader.close(); String outstring = output.toString(); LOGGER.debug("Command output:\n{}", outstring); if (!ignoreExitCode && exitCode != 0) { String msg = "Execution of command '" + command + "' failed with exit code " + exitCode; LOGGER.error("{}", msg); throw new IOException(msg); } return outstring; }
From source file:Main.java
public static int doShellCommand(String cmd, StringBuilder log, boolean runAsRoot, boolean waitFor) throws Exception { Process proc = null; int exitCode = -1; if (runAsRoot) proc = Runtime.getRuntime().exec("su"); else/*from w w w.ja va 2 s. c om*/ proc = Runtime.getRuntime().exec("sh"); OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream()); // TorService.logMessage("executing shell cmd: " + cmds[i] + "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor); out.write(cmd); out.write("\n"); out.flush(); out.write("exit\n"); out.flush(); if (waitFor) { final char buf[] = new char[10]; // Consume the "stdout" InputStreamReader reader = new InputStreamReader(proc.getInputStream()); int read = 0; while ((read = reader.read(buf)) != -1) { if (log != null) log.append(buf, 0, read); } // Consume the "stderr" reader = new InputStreamReader(proc.getErrorStream()); read = 0; while ((read = reader.read(buf)) != -1) { if (log != null) log.append(buf, 0, read); } exitCode = proc.waitFor(); } return exitCode; }
From source file:com.buaa.cfs.security.ShellBasedIdMapping.java
/** * Get the list of users or groups returned by the specified command, and save them in the corresponding map. * * @throws IOException// w w w . j a v a 2 s .c om */ @VisibleForTesting public static boolean updateMapInternal(BiMap<Integer, String> map, String mapName, String command, String regex, Map<Integer, Integer> staticMapping) throws IOException { boolean updated = false; BufferedReader br = null; try { Process process = Runtime.getRuntime().exec(new String[] { "bash", "-c", command }); br = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.defaultCharset())); String line = null; while ((line = br.readLine()) != null) { String[] nameId = line.split(regex); if ((nameId == null) || (nameId.length != 2)) { throw new IOException("Can't parse " + mapName + " list entry:" + line); } LOG.debug("add to " + mapName + "map:" + nameId[0] + " id:" + nameId[1]); // HDFS can't differentiate duplicate names with simple authentication final Integer key = staticMapping.get(parseId(nameId[1])); final String value = nameId[0]; if (map.containsKey(key)) { final String prevValue = map.get(key); if (value.equals(prevValue)) { // silently ignore equivalent entries continue; } reportDuplicateEntry("Got multiple names associated with the same id: ", key, value, key, prevValue); continue; } if (map.containsValue(value)) { final Integer prevKey = map.inverse().get(value); reportDuplicateEntry("Got multiple ids associated with the same name: ", key, value, prevKey, value); continue; } map.put(key, value); updated = true; } LOG.debug("Updated " + mapName + " map size: " + map.size()); } catch (IOException e) { LOG.error("Can't update " + mapName + " map"); throw e; } finally { if (br != null) { try { br.close(); } catch (IOException e1) { LOG.error("Can't close BufferedReader of command result", e1); } } } return updated; }
From source file:net.ftb.util.OSUtils.java
/** * Used to check if OS X is 64-bit//from w w w. java2s .c om * @return true if 64-bit OS X */ public static boolean is64BitOSX() { String line, result = ""; if (!(System.getProperty("os.version").startsWith("10.6") || System.getProperty("os.version").startsWith("10.5"))) { return true;//10.7+ only shipped on hardware capable of using 64 bit java } try { Process command = Runtime.getRuntime().exec("/usr/sbin/sysctl -n hw.cpu64bit_capable"); BufferedReader in = new BufferedReader(new InputStreamReader(command.getInputStream())); while ((line = in.readLine()) != null) { result += (line + "\n"); } } catch (Exception e) { Logger.logError("OS X bitness check failed", e); } return result.equals("1"); }
From source file:com.opentable.db.postgres.embedded.EmbeddedPostgres.java
private static List<String> system(ProcessBuilder.Redirect errorRedirector, ProcessBuilder.Redirect outputRedirector, String... command) { try {//from w w w . j av a 2s . 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:io.werval.cli.DamnSmallDevShell.java
static void rebuild(URL[] applicationClasspath, URL[] runtimeClasspath, Set<File> sourcesRoots, File classesDir) {/*w w w . j av a 2 s . c om*/ System.out.println("Compiling Application..."); String javacOutput = EMPTY; try { // Collect java files String javaFiles = EMPTY; for (File sourceRoot : sourcesRoots) { if (sourceRoot.exists()) { ProcessBuilder findBuilder = new ProcessBuilder("find", sourceRoot.getAbsolutePath(), "-type", "f", "-iname", "*.java"); Process find = findBuilder.start(); int returnCode = find.waitFor(); if (returnCode != 0) { throw new IOException("Unable to find java source files in " + sourceRoot); } javaFiles += NEWLINE + readAllAsString(find.getInputStream(), 4096, UTF_8); } } if (hasText(javaFiles)) { // Write list in a temporary file File javaListFile = new File(classesDir, ".devshell-java-list"); try (FileWriter writer = new FileWriter(javaListFile)) { writer.write(javaFiles); writer.close(); } // Compile String[] classpathStrings = new String[runtimeClasspath.length]; for (int idx = 0; idx < runtimeClasspath.length; idx++) { classpathStrings[idx] = runtimeClasspath[idx].toURI().toASCIIString(); } ProcessBuilder javacBuilder = new ProcessBuilder("javac", "-encoding", "UTF-8", "-source", "1.8", "-d", classesDir.getAbsolutePath(), "-classpath", join(classpathStrings, ":"), "@" + javaListFile.getAbsolutePath()); Process javac = javacBuilder.start(); int returnCode = javac.waitFor(); if (returnCode != 0) { throw new IOException("Unable to build java source files."); } javacOutput = readAllAsString(javac.getInputStream(), 4096, UTF_8); } } catch (InterruptedException | IOException | URISyntaxException ex) { throw new WervalException("Unable to rebuild" + (isEmpty(javacOutput) ? "" : "\n" + javacOutput), ex); } }