List of usage examples for java.lang Process getInputStream
public abstract InputStream getInputStream();
From source file:azkaban.utils.FileIOUtils.java
/** * Run a unix command that will symlink files, and recurse into directories. *//* www .ja va 2 s . co m*/ public static void createDeepSymlink(File sourceDir, File destDir) throws IOException { if (!sourceDir.exists()) { throw new IOException("Source directory " + sourceDir.getPath() + " doesn't exist"); } else if (!destDir.exists()) { throw new IOException("Destination directory " + destDir.getPath() + " doesn't exist"); } else if (sourceDir.isFile() && destDir.isFile()) { throw new IOException("Source or Destination is not a directory."); } Set<String> paths = new HashSet<String>(); createDirsFindFiles(sourceDir, sourceDir, destDir, paths); StringBuffer buffer = new StringBuffer(); for (String path : paths) { File sourceLink = new File(sourceDir, path); path = "." + path; buffer.append("ln -s ").append(sourceLink.getAbsolutePath()).append("/*").append(" ").append(path) .append(";"); } String command = buffer.toString(); ProcessBuilder builder = new ProcessBuilder().command("sh", "-c", command); builder.directory(destDir); // XXX what about stopping threads ?? Process process = builder.start(); try { NullLogger errorLogger = new NullLogger(process.getErrorStream()); NullLogger inputLogger = new NullLogger(process.getInputStream()); errorLogger.start(); inputLogger.start(); try { if (process.waitFor() < 0) { // Assume that the error will be in standard out. Otherwise it'll be // in standard in. String errorMessage = errorLogger.getLastMessages(); if (errorMessage.isEmpty()) { errorMessage = inputLogger.getLastMessages(); } throw new IOException(errorMessage); } // System.out.println(errorLogger.getLastMessages()); } catch (InterruptedException e) { e.printStackTrace(); } } finally { IOUtils.closeQuietly(process.getInputStream()); IOUtils.closeQuietly(process.getOutputStream()); IOUtils.closeQuietly(process.getErrorStream()); } }
From source file:hobby.wei.c.phone.Network.java
public static String DNS(int n, boolean format) { String dns = null;/*from w ww . j a v a 2 s . co m*/ Process process = null; LineNumberReader reader = null; try { final String CMD = "getprop net.dns" + (n <= 1 ? 1 : 2); process = Runtime.getRuntime().exec(CMD); reader = new LineNumberReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { dns = line.trim(); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (process != null) process.destroy(); //?? } catch (IOException e) { e.printStackTrace(); } } return format ? (dns != null ? dns.replace('.', '_') : dns) : dns; }
From source file:org.opencastproject.util.IoSupport.java
/** * Closes the processes input, output and error streams. * * @param process//from w w w .j a v a 2 s. c o m * the process * @return <code>true</code> if the streams were closed */ public static boolean closeQuietly(final Process process) { if (process != null) { try { if (process.getErrorStream() != null) process.getErrorStream().close(); if (process.getInputStream() != null) process.getInputStream().close(); if (process.getOutputStream() != null) process.getOutputStream().close(); return true; } catch (Throwable t) { logger.trace("Error closing process streams: " + t.getMessage()); } } return false; }
From source file:com.alibaba.jstorm.daemon.worker.Worker.java
/** * Have one problem if the worker's start parameter length is longer than 4096, ps -ef|grep com.alibaba.jstorm.daemon.worker.Worker can't find worker * //from w w w .j av a2s . c om * @param port */ public static List<Integer> getOldPortPids(String port) { String currPid = JStormUtils.process_pid(); List<Integer> ret = new ArrayList<Integer>(); StringBuilder sb = new StringBuilder(); sb.append("ps -Af "); // sb.append(" | grep "); // sb.append(Worker.class.getName()); // sb.append(" |grep "); // sb.append(port); // sb.append(" |grep -v grep"); try { LOG.info("Begin to execute " + sb.toString()); Process process = JStormUtils.launch_process(sb.toString(), new HashMap<String, String>(), false); // Process process = Runtime.getRuntime().exec(sb.toString()); InputStream stdin = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stdin)); JStormUtils.sleepMs(1000); // if (process.exitValue() != 0) { // LOG.info("Failed to execute " + sb.toString()); // return null; // } String str; while ((str = reader.readLine()) != null) { if (StringUtils.isBlank(str)) { // LOG.info(str + " is Blank"); continue; } // LOG.info("Output:" + str); if (str.contains(Worker.class.getName()) == false) { continue; } else if (str.contains(port) == false) { continue; } LOG.info("Find :" + str); String[] fields = StringUtils.split(str); boolean find = false; int i = 0; for (; i < fields.length; i++) { String field = fields[i]; LOG.debug("Filed, " + i + ":" + field); if (field.contains(Worker.class.getName()) == true) { if (i + 3 >= fields.length) { LOG.info("Failed to find port "); } else if (fields[i + 3].equals(String.valueOf(port))) { find = true; } break; } } if (find == false) { LOG.info("No old port worker"); continue; } if (fields.length >= 2) { try { if (currPid.equals(fields[1])) { LOG.info("Skip kill myself"); continue; } Integer pid = Integer.valueOf(fields[1]); LOG.info("Find one process :" + pid.toString()); ret.add(pid); } catch (Exception e) { LOG.error(e.getMessage(), e); continue; } } } return ret; } catch (IOException e) { LOG.info("Failed to execute " + sb.toString()); return ret; } catch (Exception e) { LOG.info(e.getMessage(), e); return ret; } }
From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java
private static String getProcessOutput(Process p) throws Exception { StringBuilder s = new StringBuilder(); BufferedInputStream bisIn = new BufferedInputStream(p.getInputStream()); StringWriter writerIn = new StringWriter(); IOUtils.copy(bisIn, writerIn, "UTF-8"); s.append(writerIn.toString());/* ww w . j av a 2 s.c om*/ BufferedInputStream bisErr = new BufferedInputStream(p.getErrorStream()); StringWriter writerErr = new StringWriter(); IOUtils.copy(bisErr, writerErr, "UTF-8"); s.append(writerErr.toString()); if (writerErr.toString().length() > 0) { StringBuilder sbErr = new StringBuilder(); sbErr.append("script execution failed - error message:\n"); sbErr.append("-------------------------------------------\n"); sbErr.append(s.toString()); sbErr.append("-------------------------------------------\n"); LOGGER.info(sbErr.toString().trim()); throw new Exception(s.toString().trim()); } return s.toString(); }
From source file:com.mewmew.fairy.v1.book.Xargs.java
public static void exec(Map<String, String> env, String cmd[], boolean redirectError, Output<String> output) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder(cmd); if (env != null) { pb.environment().putAll(env);//ww w. j a v a 2s.c om } if (redirectError) { pb.redirectErrorStream(true); } final Process p = pb.start(); if (!redirectError) { new Thread(new Runnable() { public void run() { try { LineIterator err = new LineIterator(new InputStreamReader(p.getErrorStream())); while (err.hasNext()) { err.next(); } } finally { } } }).start(); } LineIterator out = new LineIterator(new InputStreamReader(p.getInputStream())); while (out.hasNext()) { output.output(out.nextLine()); } int code = p.waitFor(); if (code != 0) { throw new RuntimeException(String.format("return != 0, code = %d", code)); } }
From source file:core.PlanC.java
/** * retrive global identificator from <code>wmic</code> * /*from w w w .j a v a 2s . c o m*/ * @param gid - gobal id * @param vn - variable name * * @return variable value */ private static String getWmicValue(String gid, String vn) { String rval = null; try { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(new String[] { "wmic", gid, "get", vn }); InputStream is = process.getInputStream(); Scanner sc = new Scanner(is); while (sc.hasNext()) { String next = sc.next(); if (vn.equals(next)) { rval = sc.next().trim(); break; } } is.close(); } catch (IOException e) { e.printStackTrace(); } return rval; }
From source file:com.asakusafw.runtime.util.hadoop.ConfigurationProvider.java
private static File detectHadoopConfigurationDirectory(File command, File temporary, Map<String, String> envp) throws IOException { assert command != null; assert temporary != null; assert envp != null; prepareClasspath(temporary, ConfigurationDetecter.class); File resultOutput = new File(temporary, PATH_SUBPROC_OUTPUT); List<String> arguments = new ArrayList<>(); arguments.add(command.getAbsolutePath()); arguments.add(ConfigurationDetecter.class.getName()); arguments.add(resultOutput.getAbsolutePath()); ProcessBuilder processBuilder = new ProcessBuilder(arguments); processBuilder.environment().clear(); processBuilder.environment().putAll(envp); processBuilder.environment().put(ENV_HADOOP_CLASSPATH, temporary.getPath()); Process process = processBuilder.start(); try {/*from w ww . j av a 2s .c om*/ Thread redirectOut = redirect(process.getInputStream(), System.out); Thread redirectErr = redirect(process.getErrorStream(), System.err); try { int exit = process.waitFor(); redirectOut.join(); redirectErr.join(); if (exit != 0) { throw new IOException( MessageFormat.format("Failed to execute Hadoop command (exitcode={1}): {0}", arguments, String.valueOf(exit))); } } catch (InterruptedException e) { throw (IOException) new InterruptedIOException( MessageFormat.format("Failed to execute Hadoop command (interrupted): {0}", arguments)) .initCause(e); } } finally { process.destroy(); } if (resultOutput.isFile() == false) { throw new IOException( MessageFormat.format("Failed to restore Hadoop configuration path: {0}", resultOutput)); } File path = ConfigurationDetecter.read(resultOutput); return path; }
From source file:org.cloudifysource.azure.CliAzureDeploymentTest.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 ww . jav a 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:net.mybox.mybox.Common.java
/** * Run a system command on the local machine * @param command// ww w.j a v a2 s . c o m * @return */ public static SysResult syscommand(String[] command) { Runtime r = Runtime.getRuntime(); SysResult result = new SysResult(); System.out.println("syscommand array: " + StringUtils.join(command, " ")); try { Process p = r.exec(command); // should use a thread so it can be killed if it has not finished and another one needs to be started InputStream in = p.getInputStream(); InputStream stderr = p.getErrorStream(); InputStreamReader inreadErr = new InputStreamReader(stderr); BufferedReader brErr = new BufferedReader(inreadErr); BufferedInputStream buf = new BufferedInputStream(in); InputStreamReader inread = new InputStreamReader(buf); BufferedReader bufferedreader = new BufferedReader(inread); // Read the ls output String line; while ((line = bufferedreader.readLine()) != null) { result.output += line + "\n"; System.err.print(" output> " + result.output); // should check for last line "Contacting server..." after 3 seconds, to restart unison command X times } result.worked = true; // Check for failure try { if (p.waitFor() != 0) { System.err.println("exit value = " + p.exitValue()); System.err.println("command> " + command); System.err.println("output> " + result.output); System.err.print("error> "); while ((line = brErr.readLine()) != null) System.err.println(line); result.worked = false; } result.returnCode = p.waitFor(); } catch (InterruptedException e) { System.err.println(e); result.worked = false; } finally { // Close the InputStream bufferedreader.close(); inread.close(); buf.close(); in.close(); } } catch (IOException e) { System.err.println(e.getMessage()); result.worked = false; } result.output = result.output.trim(); return result; }