List of usage examples for java.lang Process getInputStream
public abstract InputStream getInputStream();
From source file:isl.FIMS.utils.Utils.java
private static long getFreeSpaceOnWindows(String path) throws Exception { long bytesFree = -1; File script = new File(System.getProperty("java.io.tmpdir"), //$NON-NLS-1$ "script.bat"); //$NON-NLS-1$ PrintWriter writer = new PrintWriter(new FileWriter(script, false)); writer.println("dir \"" + path + "\""); //$NON-NLS-1$ //$NON-NLS-2$ writer.close();// w w w .j a va 2 s. c o m // get the output from running the .bat file Process p = Runtime.getRuntime().exec(script.getAbsolutePath()); InputStream reader = new BufferedInputStream(p.getInputStream()); StringBuffer buffer = new StringBuffer(); for (;;) { int c = reader.read(); if (c == -1) { break; } buffer.append((char) c); } String outputText = buffer.toString(); reader.close(); StringTokenizer tokenizer = new StringTokenizer(outputText, "\n"); //$NON-NLS-1$ String line = null; while (tokenizer.hasMoreTokens()) { line = tokenizer.nextToken().trim(); // see if line contains the bytes free information } tokenizer = new StringTokenizer(line, " "); //$NON-NLS-1$ tokenizer.nextToken(); tokenizer.nextToken(); bytesFree = Long.parseLong(tokenizer.nextToken().replace('.', ',').replaceAll(",", "")); //$NON-NLS-1$//$NON-NLS-2$ return bytesFree; }
From source file:com.bbxiaoqu.api.util.Utils.java
public static String submitLogs() { Process mLogcatProc = null; BufferedReader reader = null; try {//from w ww. ja va 2 s.c o m mLogcatProc = Runtime.getRuntime().exec(new String[] { "logcat", "-d", ":v" }); reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream())); String line; final StringBuilder log = new StringBuilder(); String separator = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) { log.append(line); log.append(separator); } return log.toString(); // do whatever you want with the log. I'd recommend using Intents to // create an email } catch (IOException e) { } finally { if (reader != null) try { reader.close(); } catch (IOException e) { } } return ""; }
From source file:AndroidUninstallStock.java
public static LinkedList<String> run(String... adb_and_args) throws IOException { Process pr = new ProcessBuilder(adb_and_args).redirectErrorStream(true).start(); BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); LinkedList<String> res = new LinkedList<String>(); String line;/*from w ww . j ava 2 s . co m*/ while ((line = buf.readLine()) != null) { if (!line.isEmpty()) { res.add(line); } } try { pr.waitFor(); } catch (InterruptedException e) { } return res; }
From source file:isl.FIMS.utils.Utils.java
private static long getFreeSpaceOnLinux(String path) throws Exception { long bytesFree = -1; Process p = Runtime.getRuntime().exec("df " + "/" + path); //$NON-NLS-1$ //$NON-NLS-2$ InputStream reader = new BufferedInputStream(p.getInputStream()); StringBuffer buffer = new StringBuffer(); for (;;) {// w w w. j av a 2 s .c o m int c = reader.read(); if (c == -1) { break; } buffer.append((char) c); } String outputText = buffer.toString(); reader.close(); // parse the output text for the bytes free info StringTokenizer tokenizer = new StringTokenizer(outputText, "\n"); //$NON-NLS-1$ tokenizer.nextToken(); if (tokenizer.hasMoreTokens()) { String line2 = tokenizer.nextToken(); StringTokenizer tokenizer2 = new StringTokenizer(line2, " "); //$NON-NLS-1$ if (tokenizer2.countTokens() >= 4) { tokenizer2.nextToken(); tokenizer2.nextToken(); tokenizer2.nextToken(); bytesFree = Long.parseLong(tokenizer2.nextToken()); return bytesFree * 1024; } return bytesFree * 1024; } throw new Exception("Can not read the free space of " + path + " path"); //$NON-NLS-1$ //$NON-NLS-2$ }
From source file:com.eislab.af.translator.Translator_hub_i.java
private static String findOutgoingIpV6GivenAddress(String remoteIP) throws Exception { System.out.println("remoteIP: " + remoteIP); if (remoteIP.startsWith("[")) { remoteIP = remoteIP.substring(1, remoteIP.length() - 1); System.out.println("remoteIP: " + remoteIP); }/*from ww w . ja va2 s.c o m*/ if (System.getProperty("os.name").contains("Windows")) { NetworkInterface networkInterface; //if ipv6 then find the ipaddress of the network interface String line; short foundIfIndex = 0; final String COMMAND = "route print -6"; List<RouteInfo> routes = new ArrayList<>(); try { Process exec = Runtime.getRuntime().exec(COMMAND); BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream())); //\s+addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$ Pattern p = Pattern.compile("^\\s*(\\d+)\\s+(\\d+)\\s+(.*)\\s+(.*)$"); while ((line = reader.readLine()) != null) { //do not check persistent routes. Only active routes if (line.startsWith("Persistent Routes")) { break; } Matcher match = p.matcher(line); if (match.matches()) { // System.out.println("line match: " + line); String network = match.group(3).split("/")[0]; //String mask = match.group(2); //String address = match.group(3); short maskLength = Short.valueOf(match.group(3).split("/")[1].trim()); boolean networkMatch = ipv6InRange(network, maskLength, remoteIP); if (networkMatch) { short interfaceIndex = Short.valueOf(match.group(1)); short metric = Short.valueOf(match.group(2)); routes.add(new RouteInfo("", interfaceIndex, maskLength, metric)); System.out.println("added route: " + line); } } } Collections.sort(routes); for (RouteInfo route : routes) { } if (!routes.isEmpty()) { foundIfIndex = routes.get(0).ifIndex; //based o nthe network interface index get the ip address networkInterface = NetworkInterface.getByIndex(foundIfIndex); Enumeration<InetAddress> test = networkInterface.getInetAddresses(); while (test.hasMoreElements()) { InetAddress inetaddress = test.nextElement(); if (inetaddress.isLinkLocalAddress()) { continue; } else { if (inetaddress instanceof Inet6Address) { System.out.println("interface host address: " + inetaddress.getHostAddress()); return "[" + inetaddress.getHostAddress() + "]"; } else continue; } } } else { //routes is Empty! System.out.println("No routable interface for remote IP"); throw new Exception("No routable interface for remote IP"); } } catch (Exception ex) { ex.printStackTrace(); throw ex; } } else { List<RouteInfo> routes = new ArrayList<>(); try { //ipv6 ^(.+)/(\d+)\s+(.+)\s(\d+)\s+(\d+)\s+(\d)\s+(.+)$ //ipv4 ^\s+inet\s\addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$ //linux route get command parsing: ipv4^.*via.*\s+dev\s+.*\s+src\s((?:[0-9\.]{1,3})+) //linux route get comand parsing: ipv6 ^.*\sfrom\s::\svia.*\sdev\s.*\ssrc\s((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+) //new one ^.*\s+from\s+::\s+via.*\s+dev\s+.*\ssrc\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)\s+metric\s+\d+ //final String COMMAND = "/sbin/ifconfig"; final String COMMAND = "ip route get " + remoteIP; System.out.println("command = " + COMMAND); Process exec = Runtime.getRuntime().exec(COMMAND); BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream())); System.out.println(System.getProperty("os.name")); String line; /* examples: * fdfd:55::98ac from :: via fdfd:55::98ac dev usb0 src fdfd:55::80fe metric 0 */ Pattern p = Pattern.compile( "^.*\\s+from\\s+::\\s+via.*\\sdev\\s+.*\\s+src\\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)\\s+metric\\s+\\d+.*"); //String test = "fdfd:55::80ff from :: via fdfd:55::80ff dev usb0 src fdfd:55::80fe metric 0"; while ((line = reader.readLine()) != null) { System.out.println("result of command = " + line); Matcher match = p.matcher(line); if (match.matches()) { String address = match.group(1); System.out.println("match found. address = " + address); routes.add(new RouteInfo(address, (short) 0, (short) 0, (short) 0));//metric is always 0, because we do not extract it from the ifconfig command. } } Collections.sort(routes); if (!routes.isEmpty()) return routes.get(0).source; } catch (Exception ex) { ex.printStackTrace(); } //^\s+inet6\s+addr:\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)/(\d{1,3})\s+\Scope:Global$ // NetworkInterface networkInterface; // // //if ipv6 then find the ipaddress of the network interface // String line; // short foundIfIndex = 0; // final String COMMAND = "/sbin/ifconfig"; // List<RouteInfo> routes = new ArrayList<>(); // try { // Process exec = Runtime.getRuntime().exec(COMMAND); // BufferedReader reader = new BufferedReader(new InputStreamReader(exec.getInputStream())); // //\s+addr:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Bcast:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$ // Pattern p = Pattern.compile("^\\s+inet6\\s+addr:\\s+((?:[:]{1,2}|[0-9|a|b|c|d|e|f]{1,4})+)/(\\d{1,3})\\s+\\Scope:Global$"); // while ((line = reader.readLine()) != null) { // //do not check persistent routes. Only active routes // if(line.startsWith("Persistent Routes")) { // break; // } // // Matcher match = p.matcher(line); // if (match.matches()) { // String network = match.group(1).trim(); // short maskLength = Short.valueOf(match.group(2).trim()); // // boolean networkMatch = ipv6InRange(network, maskLength, remoteIP); // // if (networkMatch) { // short interfaceIndex = Short.valueOf(match.group(1)); // short metric = Short.valueOf(match.group(2)); // routes.add(new RouteInfo("", interfaceIndex, maskLength, metric)); // System.out.println("added route: " + line); // } // } // } // Collections.sort(routes); // for (RouteInfo route : routes) { // } // // if (!routes.isEmpty()) { // foundIfIndex = routes.get(0).ifIndex; // // //based o nthe network interface index get the ip address // networkInterface = NetworkInterface.getByIndex(foundIfIndex); // // Enumeration<InetAddress> test = networkInterface.getInetAddresses(); // // while (test.hasMoreElements()) { // InetAddress inetaddress = test.nextElement(); // if (inetaddress.isLinkLocalAddress()) { // continue; // } else { // if (inetaddress instanceof Inet6Address) { // System.out.println("interface host address: " + inetaddress.getHostAddress()); // return "[" + inetaddress.getHostAddress() + "]"; // } else continue; // } // } // } else { //routes is Empty! // System.out.println("No routable interface for remote IP"); // throw new Exception("No routable interface for remote IP"); // } // } catch (Exception ex) { // ex.printStackTrace(); // throw ex; // } } return null; }
From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java
/** * Get LIST of HBOX in DHCP/*from w ww. j a v a2s .c o m*/ * * @param ip_range * @param manufacturer * @return * @throws IOException */ public static Host[] getListOfHBox_IN_DHCP(String ip_range, String manufacturer) throws IOException { ProcessBuilder pb = new ProcessBuilder("nmap", "-sP", ip_range); Process process = pb.start(); ArrayList<Host> hosts; try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line, hostname; Host host = null; Pattern pattern; Matcher matcher; hosts = new ArrayList<>(); while ((line = br.readLine()) != null) { if (host == null && line.contains("Nmap scan report for")) { pattern = Pattern.compile(IPADDRESS_PATTERN, Pattern.CASE_INSENSITIVE); matcher = pattern.matcher(line); host = new Host(); String ip_address = ""; while (matcher.find()) { ip_address += matcher.group(); } host.setIp_address(ip_address); } else if (host != null && line.matches("MAC Address: (.*) \\(" + manufacturer + "\\)")) { pattern = Pattern.compile(MACADDRESS_PATTERN, Pattern.CASE_INSENSITIVE); matcher = pattern.matcher(line); String mac_address = ""; while (matcher.find()) { mac_address += matcher.group(); } host.setMac_address(mac_address.replaceAll("\\:", "")); hostname = host.getMac_address(); hostname = hostname.substring(hostname.length() - 6, hostname.length()); host.setHost_name("HBOX-" + hostname.toLowerCase()); hosts.add(host); host = null; } } } if (!hosts.isEmpty()) { return hosts.toArray(new Host[hosts.size()]); } return null; }
From source file:eu.tango.energymodeller.datasourceclient.SlurmDataSourceAdaptor.java
/** * This executes a command and returns the output as a line of strings. * * @param cmd The command to execute//w w w. j ava 2 s . com * @return A list of output broken down by line * @throws java.io.IOException */ private static ArrayList<String> execCmd(String[] cmd) throws java.io.IOException { ArrayList<String> output = new ArrayList<>(); Process proc = Runtime.getRuntime().exec(cmd); java.io.InputStream is = proc.getInputStream(); try (java.util.Scanner scanner = new java.util.Scanner(is)) { String outputLine; while (scanner.hasNextLine()) { outputLine = scanner.nextLine(); output.add(outputLine); } } return output; }
From source file:com.moviejukebox.scanner.AttachmentScanner.java
/** * Scans a matroska movie file for attachments. * * @param movieFile the movie file to scan *///w w w . j a v a 2 s .co m private static void scanAttachments(MovieFile movieFile) { if (movieFile.isAttachmentsScanned()) { // attachments has been scanned during rescan of movie return; } // clear existing attachments movieFile.clearAttachments(); // the file with possible attachments File scanFile = movieFile.getFile(); LOG.debug("Scanning file {}", scanFile.getName()); int attachmentId = 0; try { // create the command line List<String> commandMkvInfo = new ArrayList<>(MT_INFO_EXE); commandMkvInfo.add(scanFile.getAbsolutePath()); ProcessBuilder pb = new ProcessBuilder(commandMkvInfo); // set up the working directory. pb.directory(MT_PATH); Process p = pb.start(); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = localInputReadLine(input); while (line != null) { if (line.contains("+ Attached")) { // increase the attachment id attachmentId++; // next line contains file name String fileNameLine = localInputReadLine(input); // next line contains MIME type String mimeTypeLine = localInputReadLine(input); Attachment attachment = createAttachment(attachmentId, fileNameLine, mimeTypeLine, movieFile.getFirstPart(), movieFile.getLastPart()); if (attachment != null) { attachment.setSourceFile(movieFile.getFile()); movieFile.addAttachment(attachment); } } line = localInputReadLine(input); } if (p.waitFor() != 0) { LOG.error("Error during attachment retrieval - ErrorCode={}", p.exitValue()); } } catch (IOException | InterruptedException ex) { LOG.error(SystemTools.getStackTrace(ex)); } // attachments has been scanned; no double scan of attachments needed movieFile.setAttachmentsScanned(Boolean.TRUE); }
From source file:io.siddhi.doc.gen.core.utils.DocumentationUtils.java
/** * Executing a command/*from ww w .ja va 2 s . c om*/ * * @param command The command to be executed * @param logger The maven plugin logger * @return The output lines from executing the command * @throws Throwable if any error occurs during the execution of the command */ private static List<String> getCommandOutput(String[] command, Log logger) throws Throwable { logger.info("Executing: " + String.join(" ", command)); Process process = Runtime.getRuntime().exec(command); List<String> executionOutputLines = new ArrayList<>(); // Logging the output of the command execution InputStream[] inputStreams = new InputStream[] { process.getInputStream(), process.getErrorStream() }; BufferedReader bufferedReader = null; try { for (InputStream inputStream : inputStreams) { bufferedReader = new BufferedReader(new InputStreamReader(inputStream, Constants.DEFAULT_CHARSET)); String commandOutput; while (true) { commandOutput = bufferedReader.readLine(); if (commandOutput == null) { break; } executionOutputLines.add(commandOutput); } } process.waitFor(); } finally { IOUtils.closeQuietly(bufferedReader); } return executionOutputLines; }
From source file:com.googlecode.promnetpp.research.main.CoverageMain.java
private static void doSeedRun(int seed) throws IOException, InterruptedException { currentSeed = seed;/* ww w . j ava2 s . c o m*/ System.out.println("Running with seed " + seed); String pattern = "int random = <INSERT_SEED_HERE>;"; int start = sourceCode.indexOf(pattern); int end = start + pattern.length(); String line = sourceCode.substring(start, end); line = line.replace("<INSERT_SEED_HERE>", Integer.toString(seed)); String sourceCodeWithSeed = sourceCode.replace(pattern, line); FileUtils.writeStringToFile(new File("temp.pml"), sourceCodeWithSeed); //Run Spin first List<String> spinCommand = new ArrayList<String>(); spinCommand.add(GeneralData.spinHome + "/spin"); spinCommand.add("-a"); spinCommand.add("temp.pml"); ProcessBuilder processBuilder = new ProcessBuilder(spinCommand); Process process = processBuilder.start(); process.waitFor(); //Compile PAN next List<String> compilePANCommand = new ArrayList<String>(); compilePANCommand.add("gcc"); compilePANCommand.add("-o"); compilePANCommand.add("pan"); compilePANCommand.add("pan.c"); processBuilder = new ProcessBuilder(compilePANCommand); process = processBuilder.start(); process.waitFor(); //Finally, run PAN List<String> runPANCommand = new ArrayList<String>(); runPANCommand.add("./pan"); String runtimeOptions = PANOptions.getRuntimeOptionsFor(fileName); if (!runtimeOptions.isEmpty()) { runPANCommand.add(runtimeOptions); } processBuilder = new ProcessBuilder(runPANCommand); process = processBuilder.start(); process.waitFor(); String PANOutput = Utilities.getStreamAsString(process.getInputStream()); if (PANOutputContainsErrors(PANOutput)) { throw new RuntimeException("PAN reported errors."); } processPANOutput(PANOutput); }