List of usage examples for java.lang Process getInputStream
public abstract InputStream getInputStream();
From source file:net.duckling.ddl.util.FileUtil.java
/** * Runs a simple command in given directory. * The environment is inherited from the parent process (e.g. the * one in which this Java VM runs)./*from w w w . j a v a2 s . c o m*/ * * @return Standard output from the command. * @param command The command to run * @param directory The working directory to run the command in * @throws IOException If the command failed * @throws InterruptedException If the command was halted */ public static String runSimpleCommand(String command, String directory) throws IOException, InterruptedException { StringBuffer result = new StringBuffer(); LOG.info("Running simple command " + command + " in " + directory); Process process = Runtime.getRuntime().exec(command, null, new File(directory)); BufferedReader stdout = null; BufferedReader stderr = null; try { stdout = new BufferedReader(new InputStreamReader(process.getInputStream())); stderr = new BufferedReader(new InputStreamReader(process.getErrorStream())); String line; while ((line = stdout.readLine()) != null) { result.append(line).append("\n"); } StringBuffer error = new StringBuffer(); while ((line = stderr.readLine()) != null) { error.append(line).append("\n"); } if (error.length() > 0) { LOG.error("Command failed, error stream is: " + error); } process.waitFor(); } finally { // we must close all by exec(..) opened streams: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4784692 process.getInputStream().close(); if (stdout != null) { stdout.close(); } if (stderr != null) { stderr.close(); } } return result.toString(); }
From source file:com.matze5800.paupdater.Functions.java
public static String getDevId(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Process proc; BufferedReader reader;//from w w w. java 2 s . c o m String Dev = null; try { proc = Runtime.getRuntime().exec(new String[] { "/system/bin/getprop", "ro.goo.developerid" }); reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); Dev = reader.readLine(); } catch (IOException e) { e.printStackTrace(); } if (Dev.equals(null)) { Dev = "Error parsing ro.goo.developerid!"; } Log.i("Local Parser", "Developer: " + Dev); prefs.edit().putString("Dev", Dev).commit(); return Dev; }
From source file:com.matze5800.paupdater.Functions.java
public static int getLocalVersion(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); Process proc; BufferedReader reader;/*from w w w . j a v a2s. c om*/ int localVer = 1; try { proc = Runtime.getRuntime().exec(new String[] { "/system/bin/getprop", "ro.goo.version" }); reader = new BufferedReader(new InputStreamReader(proc.getInputStream())); String result = reader.readLine(); if (result.equals("") || result.equals(null)) { Log.i("Local Parser", "Not running on PA!!!"); Log.i("Local Parser", "Disabling PA Prefs Restore"); Toast.makeText(context, "You are not running PA! You should wipe data after flash!", Toast.LENGTH_LONG).show(); prefs.edit().putBoolean("prefPrefsRestore", false).commit(); prefs.edit().putBoolean("NoPA", true).commit(); } else { localVer = Integer.valueOf(result); prefs.edit().putBoolean("NoPA", false).commit(); } Log.i("Local Parser", "Local version: " + localVer); } catch (IOException e) { Log.e("Local Parser", "Error parsing local version!"); Log.e("Local Parser", e.toString()); } return localVer; }
From source file:net.modsec.ms.connector.ConnRequestHandler.java
/** * Executes the shell scripts for starting, restarting and stopping modsecurity. * @param cmd - path of the shell script. * @param jsonResp - response to WebSiren(webapp) request. * @return jsonresponse - response to WebSiren(webapp) request. *//*from w w w . j a v a 2s. c o m*/ @SuppressWarnings("unchecked") public static JSONObject executeShScript(String cmd, JSONObject jsonResp) { log.info("starting shell script execution ... :" + cmd); try { Process process = Runtime.getRuntime().exec(cmd); String outStr = "", s = ""; BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); while ((s = br.readLine()) != null) { outStr += s; } log.info("Output String : " + outStr); String errOutput = ""; BufferedReader br2 = new BufferedReader(new InputStreamReader(process.getErrorStream())); while (br2.ready() && (s = br2.readLine()) != null) { errOutput += s; } log.info("Error String : " + errOutput); if (errOutput.contains("Syntax error")) { jsonResp.put("status", "1"); jsonResp.put("message", "Failed to start modsecurity"); } else { jsonResp.put("status", "0"); jsonResp.put("message", outStr); } } catch (IOException e) { jsonResp.put("status", "1"); jsonResp.put("message", "Error: internal service is down"); log.info("Error Message: " + e.getMessage()); //e.printStackTrace(); } return jsonResp; }
From source file:GenAppStoreSales.java
/** Connects to the AppleStore and download pending sale reports * (if they are still available)//from w w w. j a v a 2 s. c om * Requires Auntoingestion.class in the same path together with GenAppStoreSales * @throws IOException */ private static void autoingestionDownload(String reportName, String dateType, String dateCode) throws IOException { File reportFile = new File(sourcePath, reportName); Runtime rt = Runtime.getRuntime(); if (!reportFile.isFile()) { String s; System.out.println(reportName + " requesting..."); Process downloadReport = rt .exec("java Autoingestion" + autoingestionPreArgs + dateType + " " + "Summary " + dateCode); BufferedReader stdInput = new BufferedReader(new InputStreamReader(downloadReport.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(downloadReport.getErrorStream())); // read the output from the command while ((s = stdInput.readLine()) != null) System.out.println(s); // read any errors from the attempted command while ((s = stdError.readLine()) != null) System.out.println(s); // System.out.println("gzip -d " + currentPath.replace(" ", "\\ ") + "/" + reportName); // System.out.println("mv " + reportName + " " + sourcePath.replace(" ", "\\ ") + "/" + reportName); rt.exec("gzip -d " + currentPath.replace(" ", "\\ ") + "/" + reportName); rt.exec("mv " + reportName + " " + sourcePath.replace(" ", "\\ ") + "/" + reportName); rt.exec("rm " + currentPath.replace(" ", "\\ ") + "/*.gz"); } // else System.out.println(reportName + " verified"); }
From source file:com.thinkbiganalytics.spark.shell.SparkClientUtil.java
/** * Gets the Spark version string by executing {@code spark-submit}. * * @throws IOException if the version string cannot be obtained *//*from w w w.j av a2 s . c o m*/ private static String getVersion() throws IOException { // Build spark-submit process final String sparkSubmitCommand = new StringJoiner(File.separator).add(getSparkHome()).add("bin") .add("spark-submit").toString(); final Process process = new ProcessBuilder().command(sparkSubmitCommand, "--version") .redirectErrorStream(true).start(); // Wait for process to complete boolean exited; try { exited = process.waitFor(10, TimeUnit.SECONDS); } catch (final InterruptedException e) { Thread.currentThread().interrupt(); exited = !process.isAlive(); } if (!exited) { throw new IOException("Timeout waiting for Spark version"); } // Read stdout final byte[] bytes = new byte[1024]; final int length = process.getInputStream().read(bytes); final String output = new String(bytes, 0, length, "UTF-8"); final Matcher matcher = Pattern.compile("version ([\\d+.]+)").matcher(output); if (matcher.find()) { return matcher.group(1); } else { throw new IllegalStateException("Unable to determine version from Spark Submit"); } }
From source file:com.tascape.qa.th.Utils.java
public static Process cmd(String[] commands, final File file, final File workingDir, final String... ignoreRegex) throws IOException { FileUtils.touch(file);/*from w w w . java 2s . co m*/ LOG.debug("Saving console output to {}", file.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(commands); pb.redirectErrorStream(true); pb.directory(workingDir); LOG.info("Running command {}: {}", workingDir == null ? "" : workingDir.getAbsolutePath(), pb.command().toString().replaceAll(",", "")); final Process p = pb.start(); Thread t = new Thread(Thread.currentThread().getName() + "-" + p.hashCode()) { @Override public void run() { BufferedReader stdIn = new BufferedReader(new InputStreamReader(p.getInputStream())); String console = "console-" + stdIn.hashCode(); try (PrintWriter pw = new PrintWriter(file)) { for (String line = stdIn.readLine(); line != null;) { LOG.trace("{}: {}", console, line); if (null == ignoreRegex || ignoreRegex.length == 0) { pw.println(line); } else { boolean ignore = false; for (String regex : ignoreRegex) { if (!regex.isEmpty() && (line.contains(regex) || line.matches(regex))) { ignore = true; break; } } if (!ignore) { pw.println(line); } } pw.flush(); line = stdIn.readLine(); } } catch (IOException ex) { LOG.warn(ex.getMessage()); } LOG.trace("command is done"); } }; t.setDaemon(true); t.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { if (p != null) { p.destroy(); } } }); return p; }
From source file:de.teamgrit.grit.preprocess.fetch.SvnFetcher.java
/** * runSVNCommand runs an svn command in the specified directory. * * @param connection//from www . j a va2s .c o m * the connection storing the connection infos for the remote * @param svnCommand * is the command to be executed. Each part of the command must * be a string element. For example: "svn" "checkout" * "file://some/path" * @param workingDir * where the svn command should be executed (must be a * repository). * @return A list of all output lines. * @throws IOException * Thrown when process can't be started or an error occurs * while reading its output */ private static SVNResultData runSVNCommand(Connection connection, List<String> svnCommand, Path workingDir) throws IOException { // add boilerplate to command svnCommand.add("--non-interactive"); svnCommand.add("--no-auth-cache"); svnCommand.add("--force"); if ((connection.getUsername() != null) && !connection.getUsername().isEmpty()) { svnCommand.add("--username"); svnCommand.add(connection.getUsername()); } if ((connection.getPassword() != null) && !connection.getPassword().isEmpty()) { svnCommand.add("--password"); svnCommand.add(connection.getPassword()); } // build process: construct command and set working directory. Process svnProcess = null; ProcessBuilder svnProcessBuilder = new ProcessBuilder(svnCommand); svnProcessBuilder.directory(workingDir.toFile()); svnProcess = svnProcessBuilder.start(); try { svnProcess.waitFor(); } catch (InterruptedException e) { LOGGER.severe("Interrupted while waiting for SVN. " + "Cannot guarantee clean command run!"); return null; } InputStream svnOutputStream = svnProcess.getInputStream(); InputStreamReader svnStreamReader = new InputStreamReader(svnOutputStream); BufferedReader svnOutputBuffer = new BufferedReader(svnStreamReader); String line; List<String> svnOutputLines = new LinkedList<>(); while ((line = svnOutputBuffer.readLine()) != null) { svnOutputLines.add(line); } return new SVNResultData(svnProcess.exitValue(), svnOutputLines); }
From source file:jGPIO.DTO.java
/** * Tries to use lshw to detect the physical system in use. * //w w w . j a v a 2s.c o m * @return The filename of the GPIO Definitions file. */ static private String autoDetectSystemFile() { String definitions = System.getProperty("definitions.lookup"); if (definitions == null) { definitions = DEFAULT_DEFINITIONS; } File capabilitiesFile = new File(definitions); // If it doesn't exist, fall back to the default if (!capabilitiesFile.exists() && !definitions.equals(DEFAULT_DEFINITIONS)) { System.out.println("Could not find definitions lookup file at: " + definitions); System.out.println("Trying default definitions file at: " + definitions); capabilitiesFile = new File(DEFAULT_DEFINITIONS); } if (!capabilitiesFile.exists()) { System.out.println("Could not find definitions file at: " + definitions); return null; } DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = null; try { dBuilder = dbFactory.newDocumentBuilder(); } catch (ParserConfigurationException e1) { e1.printStackTrace(); } // Generate the lshw output if available Process lshw; try { lshw = Runtime.getRuntime().exec("lshw -c bus -disable dmi -xml"); lshw.waitFor(); } catch (Exception e1) { System.out.println("Couldn't execute lshw to identify board"); e1.printStackTrace(); return null; } Document lshwXML = null; try { lshwXML = dBuilder.parse(lshw.getInputStream()); } catch (IOException e1) { System.out.println("IO Exception running lshw"); e1.printStackTrace(); return null; } catch (SAXException e1) { System.out.println("Could not parse lshw output"); e1.printStackTrace(); return null; } XPath xp = XPathFactory.newInstance().newXPath(); NodeList capabilities; try { capabilities = (NodeList) xp.evaluate("/list/node[@id=\"core\"]/capabilities/capability", lshwXML, XPathConstants.NODESET); } catch (XPathExpressionException e1) { System.out.println("Couldn't run Caoability lookup"); e1.printStackTrace(); return null; } Document lookupDocument = null; try { lookupDocument = dBuilder.parse(capabilitiesFile); String lookupID = null; for (int i = 0; i < capabilities.getLength(); i++) { Node c = capabilities.item(i); lookupID = c.getAttributes().getNamedItem("id").getNodeValue(); System.out.println("Looking for: " + lookupID); NodeList nl = (NodeList) xp.evaluate("/lookup/capability[@id=\"" + lookupID + "\"]", lookupDocument, XPathConstants.NODESET); if (nl.getLength() == 1) { definitionFile = nl.item(0).getAttributes().getNamedItem("file").getNodeValue(); pinDefinitions = (JSONArray) new JSONParser().parse(new FileReader(definitionFile)); return definitionFile; } } } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.samczsun.helios.Helios.java
private static boolean ensurePython3Set0(boolean forceCheck) { String python3Location = Settings.PYTHON3_LOCATION.get().asString(); if (python3Location.isEmpty()) { SWTUtil.showMessage("You need to set the location of the Python/PyPy 3.x executable", true); setLocationOf(Settings.PYTHON3_LOCATION); python3Location = Settings.PYTHON3_LOCATION.get().asString(); }//from w w w. j a v a 2 s . co m if (python3Location.isEmpty()) { return false; } if (python3Verified == null || forceCheck) { try { Process process = new ProcessBuilder(python3Location, "-V").start(); String result = IOUtils.toString(process.getInputStream()); String error = IOUtils.toString(process.getErrorStream()); python3Verified = error.startsWith("Python 3") || result.startsWith("Python 3"); } catch (Throwable t) { t.printStackTrace(); StringWriter sw = new StringWriter(); t.printStackTrace(new PrintWriter(sw)); SWTUtil.showMessage("The Python 3.x executable is invalid." + Constants.NEWLINE + Constants.NEWLINE + sw.toString()); python3Verified = false; } } return python3Verified; }