Example #1
0
  // set adb wifi service
  public static boolean setAdbWifiStatus(boolean status) {
    Process p;
    try {
      p = Runtime.getRuntime().exec("su");

      DataOutputStream os = new DataOutputStream(p.getOutputStream());
      os.writeBytes("setprop service.adb.tcp.port " + String.valueOf(getPort()) + "\n");
      os.writeBytes("stop adbd\n");

      if (status) {
        os.writeBytes("start adbd\n");
      }
      os.writeBytes("exit\n");
      os.flush();

      p.waitFor();
      if (p.exitValue() != 255) {
        return true;
      } else {
        return false;
      }
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
 public boolean checkSetDevicePermissions() {
   java.lang.Process process = null;
   DataOutputStream os = null;
   try {
     File f = new File(MSM_DEVICE);
     if (f.canRead() && f.canWrite() /* && f1.canRead() && f1.canWrite() */) {
       return true;
     }
     process = Runtime.getRuntime().exec("su");
     os = new DataOutputStream(process.getOutputStream());
     os.flush();
     os.writeBytes("chmod 0666 " + MSM_DEVICE + "\n");
     os.flush();
     os.writeBytes("exit\n");
     os.flush();
     process.waitFor();
   } catch (Exception e) {
     return false;
   } finally {
     try {
       if (os != null) os.close();
       process.destroy();
     } catch (Exception e) {
     }
   }
   return true;
 }
Example #3
0
  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())));
  }
Example #4
0
 /**
  * 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();
 }
Example #5
0
  @Override
  public void run(PortBindings portBindings, Configuration conf, Map<String, String> parameters)
      throws IOException, InterruptedException {
    Map<String, Path> input = portBindings.getInput();
    Map<String, Path> output = portBindings.getOutput();
    FileSystem fs = FileSystem.get(conf);

    java.lang.Process process =
        Runtime.getRuntime()
            .exec(
                "python scripts/madis/mexec.py -d scripts/base_projects.db -f scripts/buildprojectdb.sql");
    BufferedOutputStream stdin = new BufferedOutputStream(process.getOutputStream());
    InputStream errorStream = process.getErrorStream();

    Iterator<Project> projects =
        DataStore.getReader(new FileSystemPath(fs, input.get(projectPort)));

    JsonStreamWriter<Project> writer = new JsonStreamWriter<Project>(Project.SCHEMA$, stdin);

    try {
      while (projects.hasNext()) {
        writer.write(projects.next());
      }
      writer.close();
      process.waitFor();
    } catch (Exception e) {
      //        	providing error details from Madis error stream
      BufferedReader stderr = new BufferedReader(new InputStreamReader(errorStream));
      StringBuilder errorBuilder = new StringBuilder();
      String line;
      while ((line = stderr.readLine()) != null) {
        errorBuilder.append(line);
      }
      stderr.close();
      throw new IOException(
          "got error while writing to Madis stream: " + errorBuilder.toString(), e);
    }

    if (process.exitValue() != 0) {
      BufferedReader stderr = new BufferedReader(new InputStreamReader(errorStream));
      StringBuilder errorBuilder = new StringBuilder();
      String line;
      while ((line = stderr.readLine()) != null) {
        errorBuilder.append(line);
      }
      stderr.close();
      throw new RuntimeException("MadIS execution failed with error: " + errorBuilder.toString());
    }

    InputStream inStream = null;
    OutputStream outStream = null;
    try {
      inStream = new FileInputStream(new File("scripts/base_projects.db"));
      outStream = fs.create(new FileSystemPath(fs, output.get(projectDBPort)).getPath());
      IOUtils.copyStream(inStream, outStream);
    } finally {
      if (inStream != null) {
        inStream.close();
      }
      if (outStream != null) {
        outStream.close();
      }
    }
  }
  /**
   * 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()
  }