Esempio n. 1
2
  protected void runScript(String[] cmd, JTextArea txaMsg) {
    String strg = "";

    if (cmd == null) return;

    Process prcs = null;
    try {
      Messages.postDebug("Running script: " + cmd[2]);
      Runtime rt = Runtime.getRuntime();

      prcs = rt.exec(cmd);

      if (prcs == null) return;

      InputStream istrm = prcs.getInputStream();
      if (istrm == null) return;

      BufferedReader bfr = new BufferedReader(new InputStreamReader(istrm));

      while ((strg = bfr.readLine()) != null) {
        // System.out.println(strg);
        strg = strg.trim();
        // Messages.postDebug(strg);
        strg = strg.toLowerCase();
        if (txaMsg != null) {
          txaMsg.append(strg);
          txaMsg.append("\n");
        }
      }
    } catch (Exception e) {
      // e.printStackTrace();
      Messages.writeStackTrace(e);
      Messages.postDebug(e.toString());
    } finally {
      // It is my understanding that these streams are left
      // open sometimes depending on the garbage collector.
      // So, close them.
      try {
        if (prcs != null) {
          OutputStream os = prcs.getOutputStream();
          if (os != null) os.close();
          InputStream is = prcs.getInputStream();
          if (is != null) is.close();
          is = prcs.getErrorStream();
          if (is != null) is.close();
        }
      } catch (Exception ex) {
        Messages.writeStackTrace(ex);
      }
    }
  }
 public static boolean testCommand(
     final Context context,
     final String command,
     final String contains,
     final List<String> arguments) {
   try {
     final List<String> commandAndArgs = new ArrayList<String>();
     commandAndArgs.add(command);
     commandAndArgs.addAll(arguments);
     final ProcessBuilder pb = new ProcessBuilder(commandAndArgs);
     logCommand(context, pb);
     final Process compilation = pb.start();
     final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), null);
     final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), null);
     compilation.waitFor();
     result.join();
     error.join();
     return error.output.toString().contains(contains)
         || result.output.toString().contains(contains);
   } catch (IOException ex) {
     context.log(ex.getMessage());
     return false;
   } catch (InterruptedException ex) {
     context.log(ex.getMessage());
     return false;
   }
 }
Esempio n. 3
0
  /**
   * Gives the same basic functionality of File.exists but can be used to look for removable media
   * without showing a system dialog if the media is not present. Workaround pulled from the <A
   * HREF="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4089199"> bug report</A> on
   * bugs.sun.com. This bug was fixed in Java 6, and we can remove the workaround when we start
   * requiring Java 6.
   */
  protected static boolean fileExists(File file) {
    try {
      Process process =
          Runtime.getRuntime().exec(new String[] {"cmd.exe", "/c", "dir", file.getAbsolutePath()});

      // We need to consume all available output or the process will block.
      boolean haveExitCode = false;
      int exitCode = -1;
      InputStream out = process.getInputStream();
      InputStream err = process.getErrorStream();

      while (!haveExitCode) {
        while (out.read() >= 0) {}
        while (err.read() >= 0) {}

        try {
          exitCode = process.exitValue();
          haveExitCode = true;
        } catch (IllegalThreadStateException e) {
          // Not yet complete.
          Thread.sleep(100);
        }
      }
      // int exitCode = process.waitFor();
      return exitCode == 0;

    } catch (IOException e) {
      System.out.println("Unable to check for file: " + file + " : " + e);
      return false;

    } catch (InterruptedException e) {
      System.out.println("Unable to check for file.  Interrupted: " + file + " : " + e);
      return false;
    }
  }
  public static void command(String command) {
    boolean err = false;

    try {
      Process process = new ProcessBuilder(command.split(" ")).start();
      BufferedReader results = new BufferedReader(new InputStreamReader(process.getInputStream()));

      String s;
      while ((s = results.readLine()) != null) {
        System.out.println(s);
      }

      BufferedReader errors = new BufferedReader(new InputStreamReader(process.getErrorStream()));

      while ((s = errors.readLine()) != null) {
        System.err.println(s);
        err = true;
      }
    } catch (IOException e) {
      // TODO 自动生成的 catch 块
      e.printStackTrace();
    }

    if (err) {
      throw new OSExecuteException("Errors executing " + command);
    }
  }
  /**
   * Executes the command through a system 'exec'. This method will be used only if the supporting
   * Java Native Interface library could not be loaded.
   */
  private synchronized void pure_exec(String[] cmd) throws IOException {
    if (null != this.environ.getExecutable()) {
      cmd[0] = this.environ.getExecutable();
    }
    p = rt.exec(cmd, this.environ.getEnvp());
    InputStream is = p.getInputStream();
    Debug.verbose("P4Process.exec().is: " + is);
    InputStreamReader isr = new InputStreamReader(is);
    Debug.verbose("P4Process.exec().isr: " + isr);
    in = new BufferedReader(isr);
    InputStream es = p.getErrorStream();
    Debug.verbose("P4Process.exec().es: " + es);
    InputStreamReader esr = new InputStreamReader(es);
    Debug.verbose("P4Process.exec().esr: " + esr);
    err = new BufferedReader(esr);

    OutputStream os = p.getOutputStream();
    Debug.verbose("P4Process.exec().os: " + os);
    OutputStreamWriter osw = new OutputStreamWriter(os);
    Debug.verbose("P4Process.exec().osw: " + osw);
    out =
        new FilterWriter(new BufferedWriter(osw)) {
          public void write(String str) throws IOException {
            super.write(str);
            System.out.print("P4DebugOutput: " + str);
          }
        };
  }
  /**
   * Creates a transcoded input stream by executing the given command. If <code>in</code> is not
   * null, data from it is copied to the command.
   *
   * @param command The command to execute.
   * @param in Data to feed to the command. May be <code>null</code>.
   * @throws IOException If an I/O error occurs.
   */
  public TranscodeInputStream(String[] command, final InputStream in) throws IOException {

    StringBuffer buf = new StringBuffer("Starting transcoder: ");
    for (String s : command) {
      buf.append('[').append(s).append("] ");
    }
    LOG.debug(buf);

    process = Runtime.getRuntime().exec(command);
    processOutputStream = process.getOutputStream();
    processInputStream = process.getInputStream();

    // Must read stderr from the process, otherwise it may block.
    final String name = command[0];
    new InputStreamReaderThread(process.getErrorStream(), name, true).start();

    // Copy data in a separate thread
    if (in != null) {
      new Thread(name + " TranscodedInputStream copy thread") {
        public void run() {
          try {
            IOUtils.copy(in, processOutputStream);
          } catch (IOException x) {
            // Intentionally ignored. Will happen if the remote player closes the stream.
          } finally {
            IOUtils.closeQuietly(in);
            IOUtils.closeQuietly(processOutputStream);
          }
        }
      }.start();
    }
  }
Esempio n. 7
0
  public static String execute(String command) {
    StringBuilder sb = new StringBuilder();
    String[] commands =
        new String[] {"/bin/bash", "-c", "export PATH=\"$PATH:/opt/local/bin\"; " + command};
    try {
      Process proc = new ProcessBuilder(commands).start();
      BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

      BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

      String s = null;
      while ((s = stdInput.readLine()) != null) {
        sb.append(s);
        sb.append("\n");
      }

      while ((s = stdError.readLine()) != null) {
        sb.append(s);
        sb.append("\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    return sb.toString();
  }
  public static void processPSOutput(Process psProcess, Processor<String> processor)
      throws IOException {
    @SuppressWarnings({"IOResourceOpenedButNotSafelyClosed"})
    BufferedReader stdOutput =
        new BufferedReader(new InputStreamReader(psProcess.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(psProcess.getErrorStream()));

    try {
      String s;
      stdOutput.readLine(); // ps output header
      while ((s = stdOutput.readLine()) != null) {
        processor.process(s);
      }

      StringBuilder errorStr = new StringBuilder();
      while ((s = stdError.readLine()) != null) {
        errorStr.append(s).append("\n");
      }
      if (errorStr.length() > 0) {
        throw new IllegalStateException("error:" + errorStr.toString());
      }
    } finally {
      stdOutput.close();
      stdError.close();
    }
  }
Esempio n. 9
0
 /** Redirect a VMs output and error streams to System.out and System.err */
 protected void redirectStreams(VirtualMachine vm) {
   MessageSiphon ms = new MessageSiphon(process.getErrorStream(), this);
   errThread = ms.getThread();
   outThread = new StreamRedirectThread("VM output reader", process.getInputStream(), System.out);
   errThread.start();
   outThread.start();
 }
  /**
   * Takes as input a GnuPlot script file path and executes this script. inside the script the user
   * can plot to screen, pause and then print to a post script file.
   *
   * @param args args[0] should be the path to the GnuPlot script file relative to the Simulator
   *     directory e.g. ./inputFiles/100C_20P_centralised/Gnuplot.gnu
   *     <p>Example Script file GnuPlot.gnu:
   *     <p>set xlabel "Lateral Displacement"; set ylabel "Contra-Lateral Displacement"; set zlabel
   *     "Amplitude" set parametric set isosamples 75,75 set contour base set cntrparam level
   *     incremental -1, 0.2, 10 set clabel '%4.2f' set contour surface set contour base; set
   *     nosurface set surface; set view 20,60 set view 60,30 set hidden3d splot u,v,sin(u)*cos(v)
   *     title "Standing Waves" set size 1.0, 0.6 set terminal postscript portrait enhanced color
   *     dashed lw 1 "Helvetica" 14 set output 'tempoutput/my-plot.ps' replot set terminal x11 set
   *     size 1,1 #pause 5
   */
  public static void gnuplot(String[] args) {

    logger.info("gnuplot called on scriptfile: " + args[0]);
    // get a Runtime object
    Runtime r = Runtime.getRuntime();

    try {
      // start the process: gnuplot
      String exe = "wgnuplot " + args[0];
      // String exe = "C:/Program Files/gnuplot/bin/wgnuplot " + args[0];
      logger.info(exe);
      Process p = r.exec(exe);

      //			any error message?
      StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERR");

      // any output?
      StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), "OUT");

      // kick them off
      errorGobbler.start();
      outputGobbler.start();

      // any error???
      int exitVal = p.waitFor();
      logger.error("ExitValue: " + exitVal);

    } catch (Exception e) {
      logger.fatal("Error Executing gnuplot: " + args[0] + " - ", e);
    }
  }
Esempio n. 11
0
  String[] getMedkit(
      String[] availableResources,
      String[] requiredResources,
      String[] missions,
      double P,
      double C) {
    try {
      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec(exec);
      OutputStream os = proc.getOutputStream();
      InputStream is = proc.getInputStream();
      new ErrorReader(proc.getErrorStream()).start();

      StringBuffer sb = new StringBuffer();
      append(sb, availableResources);
      append(sb, requiredResources);
      append(sb, missions);
      sb.append(P).append('\n');
      sb.append(C).append('\n');
      os.write(sb.toString().getBytes());

      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      int N = Integer.parseInt(br.readLine().trim());
      String[] ret = new String[N];
      for (int i = 0; i < N; i++) ret[i] = br.readLine().trim();
      return ret;

    } catch (Exception e) {
      System.err.println("An error occurred while executing your program");
      e.printStackTrace();
      return null;
    }
  }
  protected synchronized void execute(GeneralCommandLine commandLine)
      throws AuthenticationException {
    try {
      commandLine.getEnvironment().clear();
      commandLine.getEnvironment().putAll(EnvironmentUtil.getEnvironmentProperties());
      myProcess = commandLine.createProcess();

      myErrThread =
          new ReadProcessThread(
              new BufferedReader(
                  new InputStreamReader(
                      myProcess.getErrorStream(),
                      EncodingManager.getInstance().getDefaultCharset()))) {
            protected void textAvailable(String s) {
              myErrorText.append(s);
              myErrorRegistry.registerError(s);
              myContainsError = true;
            }
          };
      final Application application = ApplicationManager.getApplication();
      myStdErrFuture = application.executeOnPooledThread(myErrThread);

      myInputStream = myProcess.getInputStream();
      myOutputStream = myProcess.getOutputStream();

      waitForProcess(application);
    } catch (Exception e) {
      closeInternal();
      throw new AuthenticationException(e.getLocalizedMessage(), e);
    }
  }
Esempio n. 13
0
  private static void exec(String command) {
    try {
      System.out.println("Invoking: " + command);
      Process p = Runtime.getRuntime().exec(command);

      // get standard output
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line;
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      // get error output
      input = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      while ((line = input.readLine()) != null) {
        System.out.println(line);
      }
      input.close();

      p.waitFor();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Esempio n. 14
0
  public String[] runJob(String command) {
    outputCatcher = null;

    try {

      String[] cmd = null;
      Process proc = null;
      Runtime rt = Runtime.getRuntime();

      String os = getOsName();
      System.out.println("OS = " + os);
      if (os.startsWith("Windows")) {
        cmd = new String[3];
        cmd[0] = "cmd.exe";
        cmd[1] = "/C";
        cmd[2] = command;

        proc = rt.exec(cmd);
      } else if (os.startsWith("Linux")) {
        cmd = new String[1];
        cmd[0] = command;

        proc = rt.exec(command.split(" "));
      }

      System.out.println("command is:");
      for (int i = 0; i < cmd.length; i++) {
        System.out.print(cmd[i] + " ");
      }
      System.out.println();

      // any error message?
      errorCatcher = new StreamCatcher(proc.getErrorStream(), "ERROR");

      // any output?
      outputCatcher = new StreamCatcher(proc.getInputStream(), "OUTPUT");

      // kick them off
      errorCatcher.start();
      outputCatcher.start();

      // any error???
      exitVal = proc.waitFor();

      System.out.println("ExitValue: " + exitVal);

      if (exitVal != 0) System.out.println(errorCatcher.builder.toString());
    } catch (Throwable t) {
      t.printStackTrace();
    }

    // now return both the stdout and stderr streams
    // just use a String array for this -- not pretty but it works
    // stdout is at position [0], stderr is at [1]
    String[] outputs = new String[2];
    outputs[0] = outputCatcher.builder.toString();
    outputs[1] = errorCatcher.builder.toString();

    return outputs;
  }
 public static void logFile(String file, boolean isWrite) {
   ArrayList<String> cmds = new ArrayList<String>();
   cmds.add(Dependencies.getPythonLocation());
   cmds.add(Dependencies.getCLILocation());
   cmds.add("--file");
   cmds.add(file);
   String project = WakaTime.getProjectName();
   if (project != null) {
     cmds.add("--project");
     cmds.add(project);
   }
   cmds.add("--plugin");
   cmds.add(IDE_NAME + "/" + IDE_VERSION + " " + IDE_NAME + "-wakatime/" + VERSION);
   if (isWrite) cmds.add("--write");
   try {
     log.debug("Executing CLI: " + Arrays.toString(cmds.toArray()));
     Process proc = Runtime.getRuntime().exec(cmds.toArray(new String[cmds.size()]));
     if (WakaTime.DEBUG) {
       BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
       BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
       proc.waitFor();
       String s;
       while ((s = stdInput.readLine()) != null) {
         log.debug(s);
       }
       while ((s = stdError.readLine()) != null) {
         log.debug(s);
       }
       log.debug("Command finished with return value: " + proc.exitValue());
     }
   } catch (Exception e) {
     log.error(e);
   }
 }
Esempio n. 16
0
 public String execRecognizer() {
   try {
     String inputFile = new File(tmpdir, "input").getAbsolutePath();
     String[] args =
         new String[] {"java", "-classpath", tmpdir + pathSep + CLASSPATH, "Test", inputFile};
     // String cmdLine = "java -classpath "+CLASSPATH+pathSep+tmpdir+" Test " + new File(tmpdir,
     // "input").getAbsolutePath();
     // System.out.println("execParser: "+cmdLine);
     Process process = Runtime.getRuntime().exec(args, null, new File(tmpdir));
     StreamVacuum stdoutVacuum = new StreamVacuum(process.getInputStream());
     StreamVacuum stderrVacuum = new StreamVacuum(process.getErrorStream());
     stdoutVacuum.start();
     stderrVacuum.start();
     process.waitFor();
     stdoutVacuum.join();
     stderrVacuum.join();
     String output = null;
     output = stdoutVacuum.toString();
     if (stderrVacuum.toString().length() > 0) {
       this.stderrDuringParse = stderrVacuum.toString();
       System.err.println("exec stderrVacuum: " + stderrVacuum);
     }
     return output;
   } catch (Exception e) {
     System.err.println("can't exec recognizer");
     e.printStackTrace(System.err);
   }
   return null;
 }
 public static Either<CommandResult> runCommand(
     final Context context, final String command, final File path, final List<String> arguments) {
   try {
     final List<String> commandAndArgs = new ArrayList<String>();
     commandAndArgs.add(command);
     commandAndArgs.addAll(arguments);
     final ProcessBuilder pb = new ProcessBuilder(commandAndArgs);
     if (path != null) {
       pb.directory(path);
     }
     logCommand(context, pb);
     final Process compilation = pb.start();
     final ConsumeStream result = ConsumeStream.start(compilation.getInputStream(), context);
     final ConsumeStream error = ConsumeStream.start(compilation.getErrorStream(), context);
     final int exitCode = compilation.waitFor();
     result.join();
     error.join();
     if (result.exception != null) {
       return Either.fail(result.exception);
     }
     if (error.exception != null) {
       return Either.fail(error.exception);
     }
     return Either.success(
         new CommandResult(result.output.toString(), error.output.toString(), exitCode));
   } catch (IOException ex) {
     return Either.fail(ex);
   } catch (InterruptedException ex) {
     return Either.fail(ex);
   }
 }
Esempio n. 18
0
  // Method: runTest
  // Runs the script specified in the test case object
  public void runTest() {
    try {
      Process p = Runtime.getRuntime().exec(this.execCommandLine);

      InputStreamReader esr = new InputStreamReader(p.getErrorStream());
      BufferedReader ereader = new BufferedReader(esr);
      InputStreamReader isr = new InputStreamReader(p.getInputStream());
      BufferedReader ireader = new BufferedReader(isr);

      String line = null;
      String line1 = null;
      while ((line = ireader.readLine()) != null) {
        // System.out.println("Output: " + line);
        System.out.println(line);
      }
      while ((line1 = ereader.readLine()) != null) {
        System.err.println("Error: " + line1);
      }

      int exitValue = p.waitFor();
      tcInstanceTools.LogMessage('d', "Test Case exit value: " + exitValue);
      if (exitValue == 0) {
        setTestCaseResult(Result.Pass);
      } else {
        setTestCaseResult(Result.Fail);
      }
    } catch (IOException ioe) {
      System.out.println("Error: " + ioe.getMessage());
    } catch (InterruptedException e) {
      System.out.println("Error: " + e.getMessage());
    }
  }
    // Creates a new thread, runs the program in that thread, and reports any errors as needed.
    private void run(String clazz) {
      try {
        // Makes sure the JVM resets if it's already running.
        if (JVMrunning) kill();

        // Some String constants for java path and OS-specific separators.
        String separator = System.getProperty("file.separator");
        String path = System.getProperty("java.home") + separator + "bin" + separator + "java";

        // Tries to run compiled code.
        ProcessBuilder builder = new ProcessBuilder(path, clazz);

        // Should be good now! Everything past this is on you. Don't mess it up.
        println(
            "Build succeeded on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
        println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~", progErr);

        JVM = builder.start();

        // Note that as of right now, there is no support for input. Only output.
        Reader errorReader = new InputStreamReader(JVM.getErrorStream());
        Reader outReader = new InputStreamReader(JVM.getInputStream());
        // Writer inReader = new OutputStreamWriter(JVM.getOutputStream());

        redirectErr = redirectIOStream(errorReader, err);
        redirectOut = redirectIOStream(outReader, out);
        // redirectIn = redirectIOStream(null, inReader);
      } catch (Exception e) {
        // This catches any other errors we might get.
        println("Some error thrown", progErr);
        logError(e.toString());
        displayLog();
        return;
      }
    }
Esempio n. 20
0
 public static TByteArrayList transformByExternalCommand(
     final String command, final InputStream input) throws IOException {
   final Process process = Runtime.getRuntime().exec(command);
   final InputStream in = process.getInputStream();
   final OutputStream out = process.getOutputStream();
   final TByteArrayList bytes = new TByteArrayList(100500);
   final byte[] buffer = new byte[1024 * 1024];
   try {
     int read;
     while ((read = input.read(buffer)) > 0) {
       out.write(buffer, 0, read);
       if (in.available() > 0) {
         read = in.read(buffer);
         bytes.add(buffer, 0, read);
       }
     }
     out.close();
     while ((read = in.read(buffer)) > 0) {
       bytes.add(buffer, 0, read);
     }
     in.close();
   } catch (IOException ioe) {
     System.err.println(readByteStream(process.getErrorStream()));
     LOG.error(ioe);
     throw ioe;
   }
   return bytes;
 }
Esempio n. 21
0
  @Test
  public void testUnpack() {

    String type = "unpack";
    String path = "P:\\Ruby22-x64\\bin";
    String dir = "P:\\temp-workspace\\RPGTestProject1";
    try {
      Process process =
          Runtime.getRuntime()
              .exec(path + "\\rvpacker.bat --verbose -f -d " + dir + " -t ace -a " + type);

      new Thread(
              () -> {
                String line = null;
                int i = 0;
                try {
                  BufferedReader bR =
                      new BufferedReader(new InputStreamReader(process.getInputStream()));
                  while ((line = bR.readLine()) != null) {
                    if (line.isEmpty()) {
                      System.out.print("{E}");
                    }
                    System.out.println(++i + ": " + line);
                  }
                  System.out.println("NULL got | Closing");
                } catch (Exception e) {
                  e.printStackTrace();
                  fail("Exception");
                }
              })
          .start();
      new Thread(
              () -> {
                String line = null;
                try {
                  BufferedReader bR =
                      new BufferedReader(new InputStreamReader(process.getErrorStream()));
                  while ((line = bR.readLine()) != null) {
                    System.out.println("Err " + line);
                  }
                  System.out.println("NULL got");
                } catch (Exception e) {
                  e.printStackTrace();
                  fail("Exception");
                }
              })
          .start();
      ;

      process.waitFor();
      assertEquals(0, process.exitValue());
    } catch (IOException e) {
      e.printStackTrace();
      fail("Exception");
    } catch (InterruptedException e) {
      e.printStackTrace();
      fail("Exception");
    }
  }
Esempio n. 22
0
 private void dumpFailedLaunchInfo(Process process) {
   try {
     dumpStream(process.getErrorStream());
     dumpStream(process.getInputStream());
   } catch (IOException e) {
     MessageOutput.println("Unable to display process output:", e.getMessage());
   }
 }
Esempio n. 23
0
  protected boolean compile(String fileName) {
    String compiler = "javac";
    String classpathOption = "-classpath";

    if (jikes != null) {
      compiler = jikes;
      classpathOption = "-bootclasspath";
    }

    String[] args =
        new String[] {
          compiler,
          "-d",
          tmpdir,
          classpathOption,
          tmpdir + pathSep + CLASSPATH,
          tmpdir + "/" + fileName
        };
    String cmdLine =
        compiler
            + " -d "
            + tmpdir
            + " "
            + classpathOption
            + " "
            + tmpdir
            + pathSep
            + CLASSPATH
            + " "
            + fileName;
    // System.out.println("compile: "+cmdLine);
    File outputDir = new File(tmpdir);
    try {
      Process process = Runtime.getRuntime().exec(args, null, outputDir);
      StreamVacuum stdout = new StreamVacuum(process.getInputStream());
      StreamVacuum stderr = new StreamVacuum(process.getErrorStream());
      stdout.start();
      stderr.start();
      process.waitFor();
      stdout.join();
      stderr.join();
      if (stdout.toString().length() > 0) {
        System.err.println("compile stdout from: " + cmdLine);
        System.err.println(stdout);
      }
      if (stderr.toString().length() > 0) {
        System.err.println("compile stderr from: " + cmdLine);
        System.err.println(stderr);
      }
      int ret = process.exitValue();
      return ret == 0;
    } catch (Exception e) {
      System.err.println("can't exec compilation");
      e.printStackTrace(System.err);
      return false;
    }
  }
Esempio n. 24
0
 /**
  * processes the input String and produces an output String.
  *
  * @param input the String to input to the underlying process
  * @throws java.lang.Exception exceptions from Runtime and Process that this class uses
  * @return the output from the underlying process
  */
 public String process(String input) throws Exception {
   String returnValue = new String();
   StringBuffer buffer = new StringBuffer();
   if (socketServer == true) {
     returnValue = client.process(input);
     ServerThread current = getServer();
     if (current != null) {
       if (!current.isDaemon()) {
         current.getProcess().destroy();
       }
       current.interrupt();
     }
   } else { // not a socket server
     Runtime rt = Runtime.getRuntime();
     String output = "";
     String errors = "";
     try {
       p = rt.exec(getCodeCall() + " " + getParams());
       PrintStream processInputStream = new PrintStream(p.getOutputStream(), true, "utf-8");
       processInputStream.println(input + "\n\u0003"); // put in garbage to kill Bikel's loop
       StreamConsumer errorConsumer = new StreamConsumer(p.getErrorStream(), "error", 1);
       StreamConsumer outputConsumer = new StreamConsumer(p.getInputStream(), "output", 10);
       outputConsumer.start();
       errorConsumer.start();
       int countloops = 0;
       int time = 0;
       String message = "";
       while (!outputConsumer.isComplete()) {
         // wait
         Thread.sleep(100);
         countloops++;
         time += 100; // one tenth of a second
         if (time > waittime) { // just wait 5 minutes
           message = "exceeded waittime of " + waittime + " milliseconds";
           break;
         }
       }
       errors = errorConsumer.getOutput();
       output = outputConsumer.getOutput();
       if (!message.equals("")) {
         errors = message;
       }
     } catch (IOException ioe) {
       System.err.println("Module error: " + getModuleName());
       ioe.printStackTrace();
       System.exit(0);
     }
     p.destroy();
     if (errors.equals("")) {
       returnValue = output;
     } else {
       returnValue = errors;
     }
   }
   return returnValue;
 }
 public void run() {
   InputStream is = process.getErrorStream();
   int i = -1;
   try {
     while ((i = is.read()) != -1) {
       //	 if (showDisplay)System.out.print((char)i);
     }
   } catch (IOException ioe) {
   }
 }
Esempio n. 26
0
 private static String copyStderr(Process p) throws IOException {
   InputStream err = p.getErrorStream();
   StringBuilder result = new StringBuilder();
   byte[] buff = new byte[4096];
   int len = err.read(buff);
   while (len > 0) {
     result.append(new String(buff, 0, len));
     len = err.read(buff);
   }
   return result.toString();
 }
 private static boolean isAaptPresent() throws Exception {
   boolean result = true;
   try {
     Process proc = Runtime.getRuntime().exec("aapt");
     BufferedReader br = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
     String line = null;
     while ((line = br.readLine()) != null) {}
   } catch (Exception ex) {
     result = false;
   }
   return result;
 }
Esempio n. 28
0
  public void run() {
    Throwable tr = null;
    try {
      List<Object> cmdArray = ((List<Object>) (new ArrayList<Object>(20)));
      cmdArray.add(((Object) (SettingsAdapter.getInstance().getMPlayerCommand())));
      if (MPlayer.isChangingProcessPrioritySupported()) {
        cmdArray.add("-priority");
        cmdArray.add(((Object) (SettingsAdapter.getInstance().getMPlayerProcessPriority().name())));
      }
      cmdArray.add("-ss");
      cmdArray.add(((Object) (Long.toString(mOffset))));
      cmdArray.add(((Object) (player.mFile.getPath())));
      if (logger.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder();
        String s;
        for (Iterator<Object> iterator = cmdArray.iterator();
            iterator.hasNext();
            sb.append(s).append(' ')) s = (String) iterator.next();

        logger.debug(
            ((Object)
                ((new StringBuilder("Executing ["))
                    .append(((Object) (sb)))
                    .append("]")
                    .toString())));
      }
      mProc =
          Runtime.getRuntime()
              .exec((String[]) cmdArray.toArray(((Object[]) (new String[cmdArray.size()]))));
      logger.debug(
          ((Object) ((new StringBuilder("  as process ")).append(((Object) (mProc))).toString())));
      threadStartupDone = true;
      StreamGobbler errorGobbler = new StreamGobbler("stderr", mProc.getErrorStream());
      errorGobbler.start();
      StreamGobbler outputGobbler = new StreamGobbler("stdout", mProc.getInputStream());
      outputGobbler.start();
      int exitCode = mProc.waitFor();
      logger.debug(
          ((Object)
              ((new StringBuilder())
                  .append(((Object) (mProc)))
                  .append(" finished with exit code ")
                  .append(exitCode)
                  .toString())));
    } catch (Exception e) {
      logger.error("", ((Throwable) (e)));
      tr = ((Throwable) (e));
    } finally {
      threadStartupDone = true;
      terminated = true;
    }
    if (tr != null) player.fireExceptionEvent(tr);
  }
Esempio n. 29
0
  public static void textToMp3(String text, OutputStream os) {
    File txt = null;
    File wav = null;
    File mp3 = null;
    try {
      txt = File.createTempFile("txt", ".txt");
      FileWriter fw = new FileWriter(txt);
      fw.write(text);
      fw.close();

      wav = File.createTempFile("wav", ".wav");
      if (!wav.delete()) {
        throw new RuntimeException("couldn't delete wav");
      }
      mp3 = File.createTempFile("mp3", ".mp3");
      if (!mp3.delete()) {
        throw new RuntimeException("couldn't delete mp3");
      }

      String cmd =
          String.format(
              "/usr/bin/text2wave < %s -o %s", txt.getAbsolutePath(), wav.getAbsolutePath());

      Process p = Runtime.getRuntime().exec(new String[] {"/bin/bash", "-c", cmd});
      show(p.getErrorStream());
      System.out.println(p.waitFor()); // TODO check return code

      p =
          Runtime.getRuntime()
              .exec(new String[] {"/usr/bin/lame", wav.getAbsolutePath(), mp3.getAbsolutePath()});
      System.out.println(p.waitFor()); // TODO check return code
      FileInputStream fis = new FileInputStream(mp3);
      int read = fis.read();
      while (read != -1) {
        os.write(read);
        read = fis.read();
      }
    } catch (Throwable t) {
      throw new RuntimeException(t);
    } finally {
      // TODO check return codes
      if (mp3 != null) {
        mp3.delete();
      }
      if (txt != null) {
        txt.delete();
      }
      if (wav != null) {
        wav.delete();
      }
    }
  }
Esempio n. 30
0
  public void runMPIJob(Integer nodes) {
    try {
      String s;

      runningDir.mkdir();

      inputFile.createNewFile();
      FileWriter writer = new FileWriter(inputFile);
      writer.write(deck.toString());
      writer.close();

      logFile.createNewFile();
      writer = new FileWriter(logFile);

      String command = "mpirun ";
      command += "-np " + nodes.toString() + " ";
      command += "mcnpxMpi ";
      command += "i= " + inputFile.getPath() + " ";
      command += "o= " + outputFile.getPath() + " ";
      command += "run= " + runFile.getPath() + " ";

      Process p = Runtime.getRuntime().exec(command);
      writer.write(command + "\n");

      BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));

      BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

      while ((s = stdInput.readLine()) != null) {
        writer.write(s + '\n');
      }

      while ((s = stdError.readLine()) != null) {
        writer.write(s + '\n');
      }

      writer.close();

      String finalFilename = name + "/" + name + "_" + System.currentTimeMillis();
      new File(name).mkdir();

      inputFile.renameTo(new File(finalFilename + ".input"));
      outputFile.renameTo(new File(finalFilename + ".output"));
      runFile.renameTo(new File(finalFilename + ".run"));
      logFile.renameTo(new File(finalFilename + ".log"));

    } catch (IOException e) {
      e.printStackTrace();
      return;
    }
  }