/** * Check if the process is alive. * * @param name The process name to be checked. * @return Returns true if this process is alive, else retur false */ private boolean isProcessAlive(String name) { String cmd; String line; StringBuffer sb = new StringBuffer(); sb.append("ps "); sb.append(name); cmd = sb.toString(); try { java.lang.Process p = Runtime.getRuntime().exec(cmd); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { String[] tokens = line.split("\\s+"); if (tokens[7].equals("S")) { if (tokens[8].indexOf(name) >= 0) { Slog.w(TAG, line); return true; } } } input.close(); } catch (Exception ex) { Slog.w(TAG, ex); } return false; }
public void execMethodReadPrivateFileSystem(String path) { String line = ""; String args[] = new String[3]; args[0] = "chmod"; args[1] = "777"; args[2] = "/data/data/com.eoemobile/databases/webviewCache.db"; try { java.lang.Process process = Runtime.getRuntime().exec(args); InputStream stderr = process.getErrorStream(); InputStreamReader isrerr = new InputStreamReader(stderr); BufferedReader brerr = new BufferedReader(isrerr); InputStream outs = process.getInputStream(); InputStreamReader isrout = new InputStreamReader(outs); BufferedReader brout = new BufferedReader(isrout); String errline = null; String result = ""; while ((line = brerr.readLine()) != null) { result += line; result += "\n"; } if (result != "") { errline = result; System.out.println(errline); } while ((line = brout.readLine()) != null) { result += line; result += "\n"; } if (result != "") { System.out.println(result); } } catch (Throwable t) { t.printStackTrace(); } }
@Override public void executeShellCommand(String command, ParcelFileDescriptor sink) throws RemoteException { synchronized (mLock) { throwIfCalledByNotTrustedUidLocked(); throwIfShutdownLocked(); throwIfNotConnectedLocked(); } InputStream in = null; OutputStream out = null; try { java.lang.Process process = Runtime.getRuntime().exec(command); in = process.getInputStream(); out = new FileOutputStream(sink.getFileDescriptor()); final byte[] buffer = new byte[8192]; while (true) { final int readByteCount = in.read(buffer); if (readByteCount < 0) { break; } out.write(buffer, 0, readByteCount); } } catch (IOException ioe) { throw new RuntimeException("Error running shell command", ioe); } finally { IoUtils.closeQuietly(in); IoUtils.closeQuietly(out); IoUtils.closeQuietly(sink); } }
public static void __hx_ctor( sys.io.Process __temp_me13, java.lang.String cmd, haxe.root.Array<java.lang.String> args) { java.lang.String[] pargs = new java.lang.String[((int) ((args.length + 1)))]; pargs[0] = cmd; { int _g1 = 0; int _g = args.length; while ((_g1 < _g)) { int i = _g1++; pargs[(i + 1)] = args.__get(i); } } try { __temp_me13.proc = new java.lang.ProcessBuilder(((java.lang.String[]) (pargs))).start(); } catch (java.lang.Throwable __temp_catchallException113) { java.lang.Object __temp_catchall114 = __temp_catchallException113; if ((__temp_catchall114 instanceof haxe.lang.HaxeException)) { __temp_catchall114 = ((haxe.lang.HaxeException) (__temp_catchallException113)).obj; } { java.lang.Object e = __temp_catchall114; throw haxe.lang.HaxeException.wrap(e); } } java.lang.Process p = __temp_me13.proc; __temp_me13.stderr = new sys.io._Process.ProcessInput(((java.io.InputStream) (p.getErrorStream()))); __temp_me13.stdout = new sys.io._Process.ProcessInput(((java.io.InputStream) (p.getInputStream()))); __temp_me13.stdin = new haxe.java.io.NativeOutput(((java.io.OutputStream) (p.getOutputStream()))); }
/** * Create tombstones for the list of processes. * * @param ProcList The list of processes with ',' as a delimiter. */ private void createTombstone(String procList) { String cmd = "ps"; List<String> procList4Tombstones = new ArrayList<String>(); String line; StringBuffer sb = new StringBuffer(); sb.append(","); sb.append(procList); sb.append(","); procList = sb.toString(); try { java.lang.Process p = Runtime.getRuntime().exec(cmd); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { String[] tokens = line.split("\\s+"); if (tokens.length == 9) { String delimiter1 = "/"; String[] procname = tokens[8].split(delimiter1); StringBuffer sb1 = new StringBuffer(); sb1.append(","); sb1.append(procname[procname.length - 1]); sb1.append(","); String pn = sb1.toString(); if (procList.indexOf(pn) >= 0) { procList4Tombstones.add(tokens[1]); procList4Tombstones.add(procname[procname.length - 1]); } } } input.close(); } catch (Exception ex) { Slog.w(TAG, ex); } Iterator<String> it = procList4Tombstones.iterator(); while (it.hasNext()) { /* * Sometimes the debuggerd will exit after the tombstones creation which * will not allow the next tombstones generation. * Wait till the debuggerd is back. */ Slog.w(TAG, "Waiting for the debuggerd process..."); while (false == isProcessAlive("debuggerd")) { SystemClock.sleep(500); } String pid = it.next(); Slog.w(TAG, "Creating tombstone file for process[" + it.next() + "]"); SystemClock.sleep(1000); Process.sendSignal(Integer.parseInt(pid), 6); SystemClock.sleep(1000); Process.sendSignal(Integer.parseInt(pid), 6); SystemClock.sleep(2000); } }
// save log to file and return warning messages private String logToFile() { if (getPackageManager().checkPermission(android.Manifest.permission.READ_LOGS, getPackageName()) != 0) { return null; } DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd.HH'h'mm'm'ss's'"); String logfilename = AdPreviewer.ADPREVIEWER_DIR + this.getIntent().getExtras().getString("originalFilename") + "." + dateFormat.format(new Date()); File logfile = new File(logfilename + ".log"); File warningsLogfile = new File(logfilename + ".WARNING.log"); String pidString = null; try { Log.i(CLASSTAG, "creating log file: " + logfilename); logfile.createNewFile(); Process process = Runtime.getRuntime().exec("logcat -v time -d"); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder log = new StringBuilder(); StringBuilder warningsLog = new StringBuilder(); String line; int warningsCount = 0; while ((line = bufferedReader.readLine()) != null) { if (pidString == null && line.indexOf("AdContext") > 0) { pidString = line.substring(line.indexOf("("), line.indexOf(")") + 1); } if (pidString != null && line.indexOf(pidString) > 0) { log.append(line + "\n"); if (line.indexOf("W/") >= 0 || line.indexOf("E/") >= 0) { warningsLog.append(line + "\n"); warningsCount++; } } } BufferedWriter out = new BufferedWriter(new FileWriter(logfile)); out.write(log.toString()); out.close(); if (warningsCount > 0) { warningsLogfile.createNewFile(); BufferedWriter out2 = new BufferedWriter(new FileWriter(warningsLogfile)); out2.write(warningsLog.toString()); out2.close(); return warningsLog.toString(); } } catch (IOException e) { e.printStackTrace(); } return null; }
/** * Pipes a list of <code>Process</code> objects together like a shell pipe. * * @param proc list of processes * @return InputStream - final output */ public static java.io.InputStream pipe(java.lang.Process... proc) throws java.lang.InterruptedException { // Start Piper between all processes java.lang.Process p1; java.lang.Process p2; for (int i = 0; i < proc.length; i++) { p1 = proc[i]; // If there's one more process if (i + 1 < proc.length) { p2 = proc[i + 1]; // Start piper new Thread(new Piper(p1.getInputStream(), p2.getOutputStream())).start(); } } java.lang.Process last = proc[proc.length - 1]; // Wait for last process in chain; may throw InterruptedException last.waitFor(); // Return its InputStream return last.getInputStream(); }
/* sets the parts of speech for each node in the graph */ public void addPOS() { System.out.println("Running POS tagger..."); /* parameters for exec command */ File dir = new File("/home/josh/Desktop/Artificial_Intelligence/POS_Tagger"); /* where we are placing the file to parse */ File result = new File(file.toString() + ".pos"); int i = 1; String s = null, data = ""; try { /* command to run the POS tagger */ String command = "java -mx300m -classpath stanford-postagger.jar edu.stanford.nlp.tagger.maxent.MaxentTagger -model models/" + "bidirectional-distsim-wsj-0-18.tagger -textFile " + file.toString(); /* run the process */ Process p = Runtime.getRuntime().exec(command, null, dir); i = p.waitFor(); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); /* extract the data from the command */ while ((s = stdInput.readLine()) != null) { /* copy the data into one string */ data += s; } /* place the data in a .pos text file */ byte[] buffer = data.getBytes(); FileOutputStream fout = new FileOutputStream(result, false); fout.write(buffer); fout.close(); /* read any errors from the attempted command */ while ((s = stdError.readLine()) != null) { System.out.println(s); } } catch (Exception e) { System.out.println("Exception happened - here's what I know: "); e.printStackTrace(); System.exit(-1); } /* wait for the above process to complete */ while (i == 1) ; /* update our file to include the POS tags */ this.file = result; }
BufferedReader initialize() { BufferedReader lsofBufferedReader = null; try { process = Runtime.getRuntime().exec("lsof -F pn -i -r 1"); InputStream inputStream = process.getInputStream(); InputStreamReader inputStreamReader = new InputStreamReader(inputStream); lsofBufferedReader = new BufferedReader(inputStreamReader); } catch (Exception exception) { exception.printStackTrace(errorStream); } return lsofBufferedReader; }
// detect if adbd is running public static boolean getAdbdStatus() { int lineCount = 0; try { Process process = Runtime.getRuntime().exec("ps | grep adbd"); InputStreamReader ir = new InputStreamReader(process.getInputStream()); LineNumberReader input = new LineNumberReader(ir); String str = input.readLine(); while (str != null) { lineCount++; str = input.readLine(); } if (lineCount >= 2) { return true; } } catch (Exception e) { e.printStackTrace(); } return false; }
/** * Print report from a single command line. * * <p>TODO: Use ProcessBuilder & redirectErrorStream(true) to capture both streams (might be * important for some command lines) * * @param reportName Simple tag that will print before the report and in various annotations. * @param command Command line to execute. */ private void commandLineReport(String reportName, String command) { if (mVerbose > 0) { System.err.println(reportName + ":"); Runtime rt = Runtime.getRuntime(); Writer logOutput = null; try { // Process must be fully qualified here because android.os.Process // is used elsewhere java.lang.Process p = Runtime.getRuntime().exec(command); if (mRequestBugreport) { logOutput = new BufferedWriter( new FileWriter( new File(Environment.getExternalStorageDirectory(), reportName), true)); } // pipe everything from process stdout -> System.err InputStream inStream = p.getInputStream(); InputStreamReader inReader = new InputStreamReader(inStream); BufferedReader inBuffer = new BufferedReader(inReader); String s; while ((s = inBuffer.readLine()) != null) { if (mRequestBugreport) { logOutput.write(s); logOutput.write("\n"); } else { System.err.println(s); } } int status = p.waitFor(); System.err.println("// " + reportName + " status was " + status); if (logOutput != null) { logOutput.close(); } } catch (Exception e) { System.err.println("// Exception from " + reportName + ":"); System.err.println(e.toString()); } } }
/** * Executes a process script with the desired environment, current working directory, and * input/output streams * * <p>This implements the following CGI specification recommedations: * * <UL> * <LI>Servers SHOULD provide the "<code>query</code>" component of the script-URI as * command-line arguments to scripts if it does not contain any unencoded "=" characters and * the command-line arguments can be generated in an unambiguous manner. * <LI>Servers SHOULD set the AUTH_TYPE metavariable to the value of the "<code>auth-scheme * </code>" token of the "<code>Authorization</code>" if it was supplied as part of the * request header. See <code>getCGIEnvironment</code> method. * <LI>Where applicable, servers SHOULD set the current working directory to the directory in * which the script is located before invoking it. * <LI>Server implementations SHOULD define their behavior for the following cases: * <ul> * <LI><u>Allowed characters in pathInfo</u>: This implementation does not allow ASCII NUL * nor any character which cannot be URL-encoded according to internet standards; * <LI><u>Allowed characters in path segments</u>: This implementation does not allow * non-terminal NULL segments in the the path -- IOExceptions may be thrown; * <LI><u>"<code>.</code>" and "<code>..</code>" path segments</u>: This implementation * does not allow "<code>.</code>" and "<code>..</code>" in the the path, and such * characters will result in an IOException being thrown; * <LI><u>Implementation limitations</u>: This implementation does not impose any * limitations except as documented above. This implementation may be limited by the * servlet container used to house this implementation. In particular, all the primary * CGI variable values are derived either directly or indirectly from the container's * implementation of the Servlet API methods. * </ul> * </UL> * * For more information, see java.lang.Runtime#exec(String command, String[] envp, File dir) * * @exception IOException if problems during reading/writing occur */ public void run() throws IOException { /* * REMIND: this method feels too big; should it be re-written? */ if (!isReady()) { throw new IOException(this.getClass().getName() + ": not ready to run."); } if (debug >= 1) { log("runCGI(envp=[" + env + "], command=" + command + ")"); } if ((command.indexOf(File.separator + "." + File.separator) >= 0) || (command.indexOf(File.separator + "..") >= 0) || (command.indexOf(".." + File.separator) >= 0)) { throw new IOException( this.getClass().getName() + "Illegal Character in CGI command " + "path ('.' or '..') detected. Not " + "running CGI [" + command + "]."); } /* original content/structure of this section taken from * http://developer.java.sun.com/developer/ * bugParade/bugs/4216884.html * with major modifications by Martin Dengler */ Runtime rt = null; BufferedReader commandsStdOut = null; BufferedReader commandsStdErr = null; BufferedOutputStream commandsStdIn = null; Process proc = null; byte[] bBuf = new byte[1024]; char[] cBuf = new char[1024]; int bufRead = -1; // create query arguments Enumeration paramNames = params.keys(); StringBuffer cmdAndArgs = new StringBuffer(command); if (paramNames != null && paramNames.hasMoreElements()) { cmdAndArgs.append(" "); while (paramNames.hasMoreElements()) { String k = (String) paramNames.nextElement(); String v = params.get(k).toString(); if ((k.indexOf("=") < 0) && (v.indexOf("=") < 0)) { cmdAndArgs.append(k); cmdAndArgs.append("="); v = java.net.URLEncoder.encode(v); cmdAndArgs.append(v); cmdAndArgs.append(" "); } } } String postIn = getPostInput(params); int contentLength = (postIn.length() + System.getProperty("line.separator").length()); if ("POST".equals(env.get("REQUEST_METHOD"))) { env.put("CONTENT_LENGTH", new Integer(contentLength)); } rt = Runtime.getRuntime(); proc = rt.exec(cmdAndArgs.toString(), hashToStringArray(env), wd); /* * provide input to cgi * First -- parameters * Second -- any remaining input */ commandsStdIn = new BufferedOutputStream(proc.getOutputStream()); if (debug >= 2) { log("runCGI stdin=[" + stdin + "], qs=" + env.get("QUERY_STRING")); } if ("POST".equals(env.get("REQUEST_METHOD"))) { if (debug >= 2) { log("runCGI: writing ---------------\n"); log(postIn); log("runCGI: new content_length=" + contentLength + "---------------\n"); } commandsStdIn.write(postIn.getBytes()); } if (stdin != null) { // REMIND: document this /* assume if nothing is available after a time, that nothing is * coming... */ if (stdin.available() <= 0) { if (debug >= 2) { log("runCGI stdin is NOT available [" + stdin.available() + "]"); } try { Thread.currentThread().sleep(iClientInputTimeout); } catch (InterruptedException ignored) { } } if (stdin.available() > 0) { if (debug >= 2) { log("runCGI stdin IS available [" + stdin.available() + "]"); } bBuf = new byte[1024]; bufRead = -1; try { while ((bufRead = stdin.read(bBuf)) != -1) { if (debug >= 2) { log("runCGI: read [" + bufRead + "] bytes from stdin"); } commandsStdIn.write(bBuf, 0, bufRead); } if (debug >= 2) { log("runCGI: DONE READING from stdin"); } } catch (IOException ioe) { // REMIND: replace with logging // REMIND: should I throw this exception? log("runCGI: couldn't write all bytes."); ioe.printStackTrace(); } } } commandsStdIn.flush(); commandsStdIn.close(); /* we want to wait for the process to exit, Process.waitFor() * is useless in our situation; see * http://developer.java.sun.com/developer/ * bugParade/bugs/4223650.html */ boolean isRunning = true; commandsStdOut = new BufferedReader(new InputStreamReader(proc.getInputStream())); commandsStdErr = new BufferedReader(new InputStreamReader(proc.getErrorStream())); BufferedWriter servletContainerStdout = null; try { if (response.getOutputStream() != null) { servletContainerStdout = new BufferedWriter(new OutputStreamWriter(response.getOutputStream())); } } catch (IOException ignored) { // NOOP: no output will be written } while (isRunning) { try { // read stderr first cBuf = new char[1024]; while ((bufRead = commandsStdErr.read(cBuf)) != -1) { if (servletContainerStdout != null) { servletContainerStdout.write(cBuf, 0, bufRead); } } // set headers String line = null; while (((line = commandsStdOut.readLine()) != null) && !("".equals(line))) { if (debug >= 2) { log("runCGI: addHeader(\"" + line + "\")"); } if (line.startsWith("HTTP")) { // TODO: should set status codes (NPH support) /* * response.setStatus(getStatusCode(line)); */ } else { response.addHeader( line.substring(0, line.indexOf(":")).trim(), line.substring(line.indexOf(":") + 1).trim()); } } // write output cBuf = new char[1024]; while ((bufRead = commandsStdOut.read(cBuf)) != -1) { if (servletContainerStdout != null) { if (debug >= 4) { log("runCGI: write(\"" + cBuf + "\")"); } servletContainerStdout.write(cBuf, 0, bufRead); } } if (servletContainerStdout != null) { servletContainerStdout.flush(); } proc.exitValue(); // Throws exception if alive isRunning = false; } catch (IllegalThreadStateException e) { try { Thread.currentThread().sleep(500); } catch (InterruptedException ignored) { } } } // replacement for Process.waitFor() }
void readDatabase(String password, String filename) { // alternative: User JDBC connection for admin and 'SOURCE filename;' // (http://stackoverflow.com/questions/105776/how-do-i-restore-a-mysql-dump-file), but doesn't // work (SyntaxError) // try { // Statement stmt = adminConn.createStatement(); // int result = stmt.executeUpdate("SOURCE "+filename); // stmt.close(); // if (result == 0){ // JOptionPane.showMessageDialog(this, // "Fehler: Dump-Datei "+filename+" konnte nicht eingelesen werden.", // "Fehler", JOptionPane.ERROR_MESSAGE); // } // } catch (SQLException ex) { // System.out.println("Exception: " + ex.getMessage()); // ex.printStackTrace(); // JOptionPane.showMessageDialog(this, // "Fehler: Dump-Datei "+filename+" konnte nicht eingelesen werden.", // "Fehler", JOptionPane.ERROR_MESSAGE); // } // From: http://stackoverflow.com/questions/14691112/import-a-dump-file-to-mysql-jdbc // Use mysqlimport // String executeCmd = "mysql -u kassenadmin -p"+password+" kasse < "+filename; // String[] executeCmd = new String[] {"/bin/sh", "-c", "mysql -u kassenadmin -p"+password+" // kasse < "+filename}; String program = constructProgramPath(bc.mysqlPath, "mysql"); System.out.println("MySQL path from config.properties: *" + program + "*"); String[] executeCmd = new String[] { program, "--local-infile", "-h" + bc.mysqlHost, "-ukassenadmin", "-p" + password, "-e", "source " + filename, "kasse" }; try { Runtime shell = Runtime.getRuntime(); Process proc = shell.exec(executeCmd); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream())); System.out.println("Here is the standard output of the mysql read-in command (if any):"); String s = null; while ((s = stdInput.readLine()) != null) { System.out.println(s); } System.out.println("Here is the standard error of the mysql read-in command (if any):"); while ((s = stdError.readLine()) != null) { System.out.println(s); } int processComplete = proc.waitFor(); if (processComplete == 0) { System.out.println("Dump read in successfully"); JOptionPane.showMessageDialog( this, "Datenbank-Dump '" + filename + "' wurde erfolgreich eingelesen.", "Info", JOptionPane.INFORMATION_MESSAGE); } else { System.out.println("Could not read in the dump"); JOptionPane.showMessageDialog( this, "Fehler: Dump-Datei " + filename + " konnte nicht gelesen werden.", "Fehler", JOptionPane.ERROR_MESSAGE); } } catch (Exception ex) { ex.printStackTrace(); } }