Пример #1
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())));
  }
 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();
   }
 }
  /* 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;
  }
Пример #4
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();
      }
    }
  }
  /**
   * Performs file compression into a certain file or directory and have it inside the specified
   * destination file path.
   *
   * @param forarchive Directory or file to compress
   * @param destination Output file destination.
   * @return File information of the output file.
   */
  public java.io.File archive(java.io.File forarchive, String destination) {
    java.io.File _file = null;

    String _batchfilename = Application.startUpPath() + "\\archiver.bat";
    String _zip = mime.Mime.resources.sevenZip().getPath();
    if (_zip.startsWith("/")) _zip = mime.Mime.resources.sevenZip().getPath().substring(1);

    String _path = forarchive.getPath();
    if (_path.startsWith("/")) _path = forarchive.getPath().substring(1);

    String _contents = "\"" + _zip + "\" a \"" + destination + "\" " + _path + "\"";
    java.io.File _batchfile = null;

    StreamWriter _sw = new StreamWriter(_batchfilename);
    try {
      _sw.write(_contents);
      _batchfile = new java.io.File(_batchfilename);
    } catch (Exception ex) {
      _batchfile = null;
      ex.printStackTrace();
    } finally {
      _sw.close();
      _sw.dispose();
    }

    if (_batchfile != null) {
      java.lang.Process p = null;

      try {
        p = Runtime.getRuntime().exec(new String[] {"cmd.exe", "/C", _batchfilename});
        p.waitFor();
        InputStream _errorstream = p.getErrorStream();
        String _error = "";

        if (_errorstream != null) {
          int _bytecount = _errorstream.available();
          if (_bytecount > 0) {
            StringWriter _writer = new StringWriter();

            try {
              byte[] _bytes = new byte[_bytecount];
              _errorstream.read(_bytes);
              _error = new String(_bytes);
            } catch (Exception ex) {
              ex.printStackTrace();
            } finally {
              _writer.close();
              _writer = null;
              System.gc();
            }
          }
        }

        _file = new java.io.File(destination);
        if (!_file.exists()) {
          _file = null;
          System.gc();
        }
      } catch (Exception ex) {
        _file = null;
        ex.printStackTrace();
      } finally {
        if (p != null) p.destroy();
        p = null;
        System.gc();
      }

      try {
        _batchfile.delete();
      } catch (Exception ex) {
      } finally {
        _batchfile = null;
        System.gc();
      }
    }

    return _file;
  }
Пример #6
0
  /**
   * 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()
  }
Пример #7
0
 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();
   }
 }