List of usage examples for java.lang Process getInputStream
public abstract InputStream getInputStream();
From source file:net.ftb.util.OSUtils.java
private static byte[] genHardwareIDMACOSX() { String line;//from w w w .jav a 2s .c om try { Process command = Runtime.getRuntime().exec(new String[] { "system_profiler", "SPHardwareDataType" }); BufferedReader in = new BufferedReader(new InputStreamReader(command.getInputStream())); while ((line = in.readLine()) != null) { if (line.contains("Serial Number")) //TODO: does that more checks? { return line.split(":")[1].trim().getBytes(); } } return new byte[] {}; } catch (Exception e) { Logger.logDebug("failed", e); return new byte[] {}; } }
From source file:hobby.wei.c.phone.Network.java
public static String PING(String host, boolean format) { final int PACKAGES = 4; String info = null;/*ww w .ja va 2 s .co m*/ String print = null; Process process = null; LineNumberReader reader = null; try { final String CMD = "ping -c " + PACKAGES + " " + host; if (format) { info = "ping-c" + PACKAGES + "-" + host.replace('.', '_'); } else { print = CMD + "\n"; } process = Runtime.getRuntime().exec(CMD); reader = new LineNumberReader(new InputStreamReader(process.getInputStream())); String line = null; boolean start = false; int index = -1; while ((line = reader.readLine()) != null) { if (!format) { print += line + "\n"; } else { line = line.trim(); if (line.toLowerCase().startsWith("ping")) { line = line.substring(0, line.indexOf(')')); line = line.replace("(", ""); line = line.replace(' ', '-'); line = line.replace('.', '_'); start = true; } else if (start) { index = line.indexOf(':'); if (index > 0) { //?ttl=53 line = line.substring(index + 1).trim(); index = line.indexOf(' '); line = line.substring(index + 1, line.indexOf(' ', index + 3)).trim(); line = line.replace('=', '_'); start = false; } else { start = false; continue; } } else if (line.startsWith("" + PACKAGES)) { index = line.indexOf(','); line = line.substring(index + 1).trim(); line = line.substring(0, line.indexOf(' ')).trim(); line = line + "in" + PACKAGES + "received"; } else if (line.startsWith("rtt")) { line = line.replaceFirst(" ", "-"); line = line.replace(" ", ""); line = line.replace('/', '-'); line = line.replace('.', '_'); line = line.replace("=", "--"); } else { continue; } if (info == null) info = line; info += "--" + line; } } } catch (IOException e) { e.printStackTrace(); } finally { try { if (reader != null) reader.close(); if (process != null) process.destroy(); //?? } catch (IOException e) { //e.printStackTrace(); } } return format ? info : print; }
From source file:com.eucalyptus.storage.TGTWrapper.java
/** * executeTGTs the specified tgt command in a separate process. * A {@link DirectStorageInfo#timeoutInMillis timeout} is enforced on * the process using {@link java.util.concurrent.ExecutorService ExecutorService} * framework. If the process does not complete with in the timeout, it is cancelled. * /* w w w . jav a 2s . c o m*/ * @param command * @param timeout * @return CommandOutput * @throws EucalyptusCloudException */ private static CommandOutput execute(@NotNull String[] command, @NotNull Long timeout) throws EucalyptusCloudException, CallTimeoutException { try { Integer returnValue = -999999; Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(command); StreamConsumer error = new StreamConsumer(process.getErrorStream()); StreamConsumer output = new StreamConsumer(process.getInputStream()); error.start(); output.start(); Callable<Integer> processMonitor = new ProcessMonitor(process); Future<Integer> processController = service.submit(processMonitor); try { returnValue = processController.get(timeout, TimeUnit.MILLISECONDS); } catch (TimeoutException tex) { String commandStr = buildCommand(command); LOG.error(commandStr + " timed out. Cancelling the process, logging a fault and exceptioning out"); processController.cancel(true); Faults.forComponent(Storage.class).havingId(TGT_HOSED).withVar("component", "Storage Controller") .withVar("timeout", Long.toString(timeout)).log(); throw new CallTimeoutException("No response from the command " + commandStr + ". Process timed out after waiting for " + timeout + " milliseconds"); } output.join(); error.join(); LOG.debug("TGTWrapper executed: " + JOINER.join(command) + "\n return=" + returnValue + "\n stdout=" + output.getReturnValue() + "\n stderr=" + error.getReturnValue()); return new CommandOutput(returnValue, output.getReturnValue(), error.getReturnValue()); } catch (CallTimeoutException e) { throw e; } catch (Exception ex) { throw new EucalyptusCloudException(ex); } }
From source file:Main.java
public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor) throws Exception { Process proc = null; int exitCode = -1; if (runAsRoot) { proc = Runtime.getRuntime().exec("su"); } else {// w w w . j ava 2 s. c om proc = Runtime.getRuntime().exec("sh"); } OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream()); for (int i = 0; i < cmds.length; i++) { // TorService.logMessage("executing shell cmd: " + cmds[i] + // "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor); out.write(cmds[i]); 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:org.kaaproject.kaa.sandbox.web.services.SandboxServiceImpl.java
private static String executeCommand(String... command) throws SandboxServiceException { StringBuilder output = new StringBuilder(); Process process;/* ww w .j a va 2 s.c om*/ try { process = Runtime.getRuntime().exec(command); process.waitFor(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line = ""; while ((line = reader.readLine()) != null) { output.append(line).append("\n"); } } } catch (Exception ex) { throw Utils.handleException(ex); } return output.toString(); }
From source file:com.piusvelte.taplock.server.TapLockServer.java
protected static String getToggleAction() { String command = null;//from w w w . j ava2 s . com if (OS == OS_NIX) { command = "gnome-screensaver-command -q"; Process p = null; try { p = Runtime.getRuntime().exec(command); } catch (IOException e) { writeLog("Runtime.getRuntime().exec: " + e.getMessage()); } if (p != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; try { line = reader.readLine(); } catch (IOException e) { writeLog("reader.readLine: " + e.getMessage()); } while (line != null) { if (line.contains("inactive")) return ACTION_LOCK; else return ACTION_UNLOCK; } return ACTION_UNLOCK; } } return ACTION_LOCK; }
From source file:net.centro.rtb.monitoringcenter.metrics.system.os.OperatingSystemMetricSet.java
private static Double fetchIoWaitPercentage() { // Only Linux is supported if (!SystemUtils.IS_OS_LINUX) { return null; }/*from w w w . java2 s .c o m*/ try { // Take the second sample from iostat, as the first one is a static value acquired at the machine start-up Process process = Runtime.getRuntime() .exec(new String[] { "bash", "-c", "iostat -c 1 2 | awk '/^ /{print $4}'" }); BufferedReader errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream())); BufferedReader resultStream = new BufferedReader(new InputStreamReader(process.getInputStream())); List<String> outputLines = new ArrayList<>(); String line = null; while ((line = resultStream.readLine()) != null) { outputLines.add(line); } boolean error = false; while (errorStream.readLine() != null) { error = true; } errorStream.close(); resultStream.close(); try { int result = process.waitFor(); if (result != 0) { logger.debug("iostat failed with return code {}", result); } } catch (InterruptedException e) { logger.debug("iostat was interrupted"); } if (!error && outputLines.size() == 2) { String iowaitPercentStr = outputLines.get(outputLines.size() - 1); try { return Double.parseDouble(iowaitPercentStr); } catch (NumberFormatException e) { logger.debug("Error parsing iowait value from {}", iowaitPercentStr); } } } catch (Exception e) { logger.debug("Exception occurred while executing iostat command", e); if (InterruptedException.class.isInstance(e)) { Thread.currentThread().interrupt(); } } return null; }
From source file:elh.eus.absa.NLPpipelineWrapper.java
public static int eustaggerCall(String taggerCommand, String string, String fname) { try {/*from w w w .j av a 2s. c om*/ File temp = new File(fname); //System.err.println("eustaggerCall: created temp file: "+temp.getAbsolutePath()); BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); bw.write(string + "\n"); bw.close(); String[] command = { taggerCommand, temp.getName() }; System.err.println("Eustagger agindua: " + Arrays.toString(command)); ProcessBuilder eustBuilder = new ProcessBuilder().command(command); eustBuilder.directory(new File(temp.getParent())); //.redirectErrorStream(true); Process eustagger = eustBuilder.start(); int success = eustagger.waitFor(); //System.err.println("eustagger succesful? "+success); if (success != 0) { System.err.println("eustaggerCall: eustagger error"); } else { String tagged = fname + ".kaf"; BufferedReader reader = new BufferedReader(new InputStreamReader(eustagger.getInputStream())); //new Eustagger_lite outputs to stdout. Also called ixa-pipe-pos-eu if (taggerCommand.contains("eustagger") || taggerCommand.contains("ixa-pipe")) { Files.copy(eustagger.getInputStream(), Paths.get(tagged)); } // old eustagger (euslem) else { FileUtilsElh.renameFile(temp.getAbsolutePath() + ".etiketatua3", tagged); } } // // delete all temporal files used in the process. temp.delete(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); return -1; } return 0; }
From source file:com.att.android.arodatacollector.utils.AROCollectorUtils.java
/** * find the process info/* w w w. jav a2 s . c om*/ * @param processName * @return * @throws IOException * @throws InterruptedException */ public static String executePS(String processName) throws IOException, InterruptedException { AROLogger.d(TAG, "entered ps..."); final Process process = Runtime.getRuntime().exec("ps " + processName); final InputStreamReader inputStream = new InputStreamReader(process.getInputStream()); final BufferedReader reader = new BufferedReader(inputStream); try { String line = null; int read; final char[] buffer = new char[4096]; final StringBuffer output = new StringBuffer(); while ((read = reader.read(buffer)) > 0) { output.append(buffer, 0, read); } // Waits for the command to finish. process.waitFor(); //no need to destroy the process since waitFor() will wait until all subprocesses exit line = output.toString(); return line; } finally { try { reader.close(); inputStream.close(); reader.close(); } catch (Exception e) { AROLogger.e(TAG, "Exception caught while closing resources in executePS. Error msg=" + e.getMessage()); AROLogger.e(TAG, "execution will be allowed to continue"); } AROLogger.d(TAG, "exiting ps..."); } }
From source file:Main.java
public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor) throws Exception { Process proc = null; int exitCode = -1; if (runAsRoot) proc = Runtime.getRuntime().exec("su"); else/* ww w . ja v a2 s .c o m*/ proc = Runtime.getRuntime().exec("sh"); OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream()); for (int i = 0; i < cmds.length; i++) { Log.d("the-onion-phone", "executing shell cmd: " + cmds[i] + "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor); out.write(cmds[i]); 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; }