Exemplo 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);
      }
    }
  }
Exemplo n.º 2
0
Arquivo: Macro.java Projeto: bramk/bnd
  /**
   * System command. Execute a command and insert the result.
   *
   * @param args
   * @param help
   * @param patterns
   * @param low
   * @param high
   */
  public String system_internal(boolean allowFail, String args[]) throws Exception {
    verifyCommand(
        args,
        "${"
            + (allowFail ? "system-allow-fail" : "system")
            + ";<command>[;<in>]}, execute a system command",
        null,
        2,
        3);
    String command = args[1];
    String input = null;

    if (args.length > 2) {
      input = args[2];
    }

    Process process = Runtime.getRuntime().exec(command, null, domain.getBase());
    if (input != null) {
      process.getOutputStream().write(input.getBytes("UTF-8"));
    }
    process.getOutputStream().close();

    String s = IO.collect(process.getInputStream(), "UTF-8");
    int exitValue = process.waitFor();
    if (exitValue != 0) return exitValue + "";

    if (!allowFail && (exitValue != 0)) {
      domain.error("System command " + command + " failed with " + exitValue);
    }
    return s.trim();
  }
Exemplo n.º 3
0
  private IdedProtos.Response processRequest(IdedProtos.Request request) {
    try {
      request.writeDelimitedTo(process.getOutputStream());
      process.getOutputStream().flush();

      lock.lock();
      try {
        for (; ; ) {
          if (error != null) {
            throw new RuntimeException(error);
          }

          if (response != null) {
            IdedProtos.Response response = this.response;
            this.response = null;
            return response;
          }

          condition.await();
        }
      } finally {
        lock.unlock();
      }

    } catch (InterruptedException e) {
      throw new RuntimeException(e);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 4
0
 public static void startS3270() throws IOException {
   s3270 = Runtime.getRuntime().exec(WrapperCodes.PROGRAM_NAME);
   read = new BufferedReader(new InputStreamReader(s3270.getInputStream()));
   write = new PrintWriter(new OutputStreamWriter(s3270.getOutputStream()));
   startTareas();
   writeInS3270(WrapperCodes.PRINTTEXT, true);
 }
Exemplo n.º 5
0
  /**
   * 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();
    }
  }
Exemplo n.º 7
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;
 }
Exemplo n.º 8
0
 public static int runA2sd(int mode) {
   String command = "";
   if (mode == 0) // remove a2sd
   command = "echo \"n\" | /system/bin/a2sd remove";
   else if (mode == 1) // a2sd
   command = "echo \"n\" | /system/bin/a2sd install";
   else if (mode == 2) // dc2sd
   command = "echo \"y\" | /system/bin/a2sd install";
   if (!command.equals("")) {
     try {
       Process process = Runtime.getRuntime().exec("su");
       Log.e(TAG, "Executing: " + command);
       DataOutputStream outputStream = new DataOutputStream(process.getOutputStream());
       DataInputStream inputStream = new DataInputStream(process.getInputStream());
       outputStream.writeBytes(command + "\n");
       outputStream.flush();
       outputStream.writeBytes("exit\n");
       outputStream.flush();
       process.waitFor();
     } catch (IOException e) {
       return -1;
     } catch (InterruptedException e) {
       return -2;
     }
     return 0;
   }
   return -3;
 }
Exemplo n.º 9
0
  public boolean executeFilter(@NotNull Editor editor, @NotNull TextRange range, String command)
      throws IOException {
    if (logger.isDebugEnabled()) logger.debug("command=" + command);
    CharSequence chars = editor.getDocument().getCharsSequence();
    StringReader car =
        new StringReader(
            chars.subSequence(range.getStartOffset(), range.getEndOffset()).toString());
    StringWriter sw = new StringWriter();

    logger.debug("about to create filter");
    Process filter = Runtime.getRuntime().exec(command);
    logger.debug("filter created");
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(filter.getOutputStream()));
    logger.debug("sending text");
    copy(car, writer);
    writer.close();
    logger.debug("sent");

    BufferedReader reader = new BufferedReader(new InputStreamReader(filter.getInputStream()));
    logger.debug("getting result");
    copy(reader, sw);
    sw.close();
    logger.debug("received");

    editor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), sw.toString());

    lastCommand = command;

    return true;
  }
Exemplo n.º 10
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);
    }
  }
Exemplo n.º 12
0
 // To be called exactly twice by the parent process
 static <T> T rendezvousParent(Process p, Callable<T> callable) throws Throwable {
   p.getInputStream().read();
   T result = callable.call();
   OutputStream os = p.getOutputStream();
   os.write((byte) '\n');
   os.flush();
   return result;
 }
Exemplo n.º 13
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;
 }
Exemplo n.º 14
0
  /*
   * (non-Javadoc)
   *
   * @see com.tek42.perforce.process.P4Executor#exec(java.lang.String[])
   */
  public void exec(String[] args) throws PerforceException {
    this.args.clear();
    StringBuilder debug = new StringBuilder();
    for (String arg : args) {
      debug.append(arg + " ");
      this.args.add(arg);
    }
    logger.info("Executing: " + debug);
    builder.redirectErrorStream(true);
    try {
      currentProcess = builder.start();
      input = currentProcess.getInputStream();
      output = currentProcess.getOutputStream();
      reader = new BufferedReader(new InputStreamReader(currentProcess.getInputStream()));
      writer = new BufferedWriter(new OutputStreamWriter(currentProcess.getOutputStream()));

    } catch (IOException e) {
      throw new PerforceException("Failed to open connection to: " + args[0], e);
    }
  }
Exemplo n.º 15
0
 private void spawnProcess() throws DCDError {
   GeneralCommandLine commandLine = new GeneralCommandLine(path);
   commandLine.setWorkDirectory(workingDirectory);
   commandLine.setRedirectErrorStream(true);
   try {
     process = commandLine.createProcess();
   } catch (ExecutionException e) {
     throw new InitError(e.toString());
   }
   input = new BufferedReader(new InputStreamReader(process.getInputStream()));
   output = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
 }
Exemplo n.º 16
0
  /**
   * Launch the specified call list.
   *
   * @param callList launch the call list
   * @return {@code true} in case the launch was successful
   */
  private boolean launchCallList(final List<String> callList) {
    try {
      final ProcessBuilder pBuilder = new ProcessBuilder(callList);

      File workingDirectory = DirectoryManager.getInstance().getWorkingDirectory();
      if (workingDirectory != null) {
        pBuilder.directory(workingDirectory);
      }
      pBuilder.redirectErrorStream(true);
      final Process proc = pBuilder.start();
      proc.getOutputStream().close();

      final StringBuilder outputBuffer = new StringBuilder();
      outputReader = new BufferedReader(new InputStreamReader(proc.getInputStream()));

      launchTimer.start();
      cancelExecution = false;

      while (true) {
        if (cancelExecution) {
          throw new IOException("Response Timeout.");
        }
        final String line = outputReader.readLine();
        if (line == null) {
          errorData = outputBuffer.toString().trim();
          return false;
        }
        if (line.endsWith("Startup done.")) {
          outputReader.close();
          return true;
        }
        outputBuffer.append(line);
        outputBuffer.append('\n');
      }
    } catch (@Nonnull final Exception e) {
      final StringWriter sWriter = new StringWriter();
      final PrintWriter writer = new PrintWriter(sWriter);
      e.printStackTrace(writer);
      writer.flush();
      errorData = sWriter.toString();
      return false;
    } finally {
      if (outputReader != null) {
        try {
          outputReader.close();
        } catch (@Nonnull final IOException e) {
          // nothing
        }
      }
      outputReader = null;
    }
  }
Exemplo n.º 17
0
  private String getFullWmicResult(String alias, String verb, String property) {
    StringBuilder res = new StringBuilder();
    BufferedReader in = null;
    BufferedWriter bw = null;
    try {
      ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "WMIC", alias, verb, property);
      Process p = pb.start();
      // need this for executing windows commands (at least
      // needed for executing wmic command)
      bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
      bw.write(13);
      bw.flush();

      p.waitFor();
      if (p.exitValue() == 0) {
        in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
          line = line.trim();
          if (line.length() == 0) {
            continue;
          }
          if (line.toLowerCase(Locale.US).indexOf(property.toLowerCase(Locale.US)) != -1) {
            continue;
          }
          res.append(line).append("\n");
        }
      }

    } catch (Exception e) {
      // ignore the exception
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // ignore
        }
      }

      if (bw != null) {
        try {
          bw.close();
        } catch (IOException e) {
          // ignore
        }
      }
    }
    return res.toString();
  }
Exemplo n.º 18
0
 public boolean continueShellProcess(Process proc) {
   if (progIndicator.isAborted()) {
     try {
       Writer stream;
       stream = new OutputStreamWriter((BufferedOutputStream) proc.getOutputStream());
       stream.write((char) 3);
       stream.flush();
       stream.close();
     } catch (IOException e) {
     }
     return false;
   }
   return true;
 }
Exemplo n.º 19
0
  /**
   * This method invokes wmic outside of the normal environment collection routines.
   *
   * <p>An initial call to wmic can be costly in terms of time. <code>
   * Details of why the first call is costly can be found at:
   *
   * http://support.microsoft.com/kb/290216/en-us
   *
   * "When you run the Wmic.exe utility for the first time, the utility
   * compiles its .mof files into the repository. To save time during
   * Windows installation, this operation takes place as necessary."
   * </code>
   */
  private String getWmicResult(String alias, String verb, String property) {
    String res = "";
    BufferedReader in = null;
    BufferedWriter bw = null;
    try {
      ProcessBuilder pb = new ProcessBuilder("cmd", "/C", "WMIC", alias, verb, property);
      Process p = pb.start();
      // need this for executing windows commands (at least
      // needed for executing wmic command)
      bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
      bw.write(13);

      p.waitFor();
      if (p.exitValue() == 0) {
        in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;
        while ((line = in.readLine()) != null) {
          line = line.trim();
          if (line.length() == 0) {
            continue;
          }
          res = line;
        }
        // return the *last* line read
        return res;
      }

    } catch (Exception e) {
      // ignore the exception
    } finally {
      if (in != null) {
        try {
          in.close();
        } catch (IOException e) {
          // ignore
        }
      }
      if (bw != null) {
        try {
          bw.flush();
        } catch (Exception ex) { // ignore...
        }
        try {
          bw.close();
        } catch (Exception ex) { // ignore...
        }
      }
    }
    return res.trim();
  }
Exemplo n.º 20
0
  public void start() {
    Runtime runtime = Runtime.getRuntime();

    try {
      process = runtime.exec(command);
      reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
      writer = new PrintWriter(new OutputStreamWriter(process.getOutputStream()), true);
      runtime.addShutdownHook(
          new Thread() {
            @Override
            public void run() {
              cleanup();
            }
          });
    } catch (IOException ex) {
      ex.printStackTrace();
    }
  }
Exemplo n.º 21
0
  /** Execute the process and return when the process is complete. */
  public void exec() throws IOException {
    Runtime rt = Runtime.getRuntime();

    try {
      Process proc = rt.exec(commandLine);
      OutputStream os = rt.getLocalizedOutputStream(proc.getOutputStream());

      if (this.observer instanceof RefEnv) {
        os.write("quit();\n".getBytes());
      }

      os.flush();
      os.close();

      InputStreamReader is;

      is = new InputStreamReader(proc.getErrorStream());
      (new Thread(new StreamReader(error, is))).start();

      is = new InputStreamReader(proc.getInputStream());
      (new Thread(new StreamReader(input, is))).start();

      proc.waitFor();
      exitValue = proc.exitValue();

      // unfortunately the following pause seems to
      // need to be here otherwise we get a crash

      // On AIX, Process.waitFor() doesn't seem to wait for
      // the process to complete before continuing.  Bad.
      // Need to find a workaround.

      if (System.getProperty("os.name").startsWith("AIX")
          || System.getProperty("os.name").startsWith("HP")) {
        pause(20000);
      } else {
        pause(10000);
      }

    } catch (Exception e) {
      java.lang.System.out.println(e);
      e.printStackTrace();
    }
  }
  /**
   * Process the blog entries
   *
   * @param httpServletRequest Request
   * @param httpServletResponse Response
   * @param blog {@link Blog} instance
   * @param context Context
   * @param entries Blog entries retrieved for the particular request
   * @return Modified set of blog entries
   * @throws PluginException If there is an error processing the blog entries
   */
  public Entry[] process(
      HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse,
      Blog blog,
      Map context,
      Entry[] entries)
      throws PluginException {
    if (!BlojsomUtils.checkNullOrBlank(_markdownExecution)) {
      for (int i = 0; i < entries.length; i++) {
        Entry entry = entries[i];

        if ((entry.getPostSlug().endsWith(MARKDOWN_EXTENSION)
            || BlojsomUtils.checkMapForKey(entry.getMetaData(), METADATA_RUN_MARKDOWN))) {
          try {
            Process process = Runtime.getRuntime().exec(_markdownExecution);
            BufferedWriter bw =
                new BufferedWriter(
                    new OutputStreamWriter(process.getOutputStream(), BlojsomConstants.UTF8));
            BufferedReader br =
                new BufferedReader(
                    new InputStreamReader(process.getInputStream(), BlojsomConstants.UTF8));
            bw.write(entry.getDescription());
            bw.close();
            String input;
            StringBuffer collectedDescription = new StringBuffer();

            while ((input = br.readLine()) != null) {
              collectedDescription.append(input).append(BlojsomConstants.LINE_SEPARATOR);
            }

            entry.setDescription(collectedDescription.toString());
            br.close();
          } catch (IOException e) {
            if (_logger.isErrorEnabled()) {
              _logger.error(e);
            }
          }
        }
      }
    }

    return entries;
  }
Exemplo n.º 23
0
  public static void main(String args[]) {

    //        ProcessBuilder pb = new
    // ProcessBuilder("/Users/musictechnology/Documents/Kinect/OpenNI-Bin-Dev-MacOSX-v1.5.7.10/Samples/Bin/x64-Release/Sample-NiSimpleRead");
    //        pb.directory(new
    // File("/Users/musictechnology/Documents/Kinect/OpenNI-Bin-Dev-MacOSX-v1.5.7.10/Samples/Bin/x64-Release/"));
    ProcessBuilder pb =
        new ProcessBuilder(
            "/Users/musictechnology/Documents/Kinect/NITE-Bin-Dev-MacOSX-v1.5.2.21/Samples/Bin/x64-Release/Sample-Players");
    pb.directory(
        new File(
            "/Users/musictechnology/Documents/Kinect/NITE-Bin-Dev-MacOSX-v1.5.2.21/Samples/Bin/x64-Release/"));
    try {
      Process process = pb.start();
      String line;

      BufferedReader is = new BufferedReader(new InputStreamReader(process.getInputStream()));
      //            while ((line = is.readLine()) != null) {
      //                System.out.println(line);
      //            }
      //            while (is.readLine() != null) {
      //                System.out.println(is.readLine());
      //            }
      //            System.out.flush();

      // Maybe use event listener to listen, then do something

      OutputStream output = process.getOutputStream();
      //            BufferedWriter bufferedWriter = new BufferedWriter(stderr);
      PrintWriter pw = new PrintWriter(output);
      while (true) {
        pw.flush();
        Thread.sleep(1000);
      }

    } catch (IOException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 24
0
  /**
   * Executes a command as {@code user}. Saves the stdout/stderr in the corresponding fields and
   * returns the return code of the child process.
   *
   * @param cmd The command to execute
   * @param data The data to send to the stdin of the process
   * @param timelimt How many seconds the command can run
   * @param memlimit How many megabytes the command can use
   */
  private int exec(String cmdS, String data, int timelimit, int memlimit) throws Exception {
    ArrayList<String> cmd = new ArrayList<String>(cmdPrefix);
    cmd.add("-m");
    cmd.add("" + memlimit);
    cmd.add("-c");
    cmd.add("" + timelimit);
    cmd.add("-w");
    cmd.add("" + (3 * timelimit + 1));
    cmd.add("-x");
    cmd.add(cmdS);
    String tmp = "";
    for (String cs : cmd) tmp += " \"" + cs + "\"";
    log.fine("exec " + tmp);
    ProcessBuilder pb = new ProcessBuilder(cmd);
    pb.directory(workDir);
    Process p = pb.start();
    OutputStreamWriter writer = new OutputStreamWriter(p.getOutputStream());
    StreamReader rOut = new StreamReader(p.getInputStream());
    StreamReader rErr = new StreamReader(p.getErrorStream());
    rOut.start();
    rErr.start();

    // TODO I think this may block for big tests. Check and Fix.
    // send and receive data "in parallel"
    writer.write(data);
    writer.flush();
    writer.close();
    rOut.join();
    rErr.join();
    stdout = rOut.result;
    stderr = rErr.result;
    if (rOut.exception != null) throw rOut.exception;
    if (rErr.exception != null) throw rErr.exception;

    // log.finer("out: " + stdout);
    // log.finer("err: " + stderr);
    // log.finer("done exec");
    return p.waitFor();
  }
  private void startProcess() throws IOException, SrvrMgrException {
    ProcessBuilder builder = new ProcessBuilder(runTimeCommand);
    this.lastCommandDate = System.currentTimeMillis();
    try {
      builder.redirectErrorStream(true);
      this.process = builder.start();
    } catch (Exception ex) {
      throw new SrvrMgrException("Can't start process " + Arrays.toString(runTimeCommand));
    }
    this.locked = false;
    this.processInput = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
    this.processOutputStream = process.getInputStream();
    this.PID = getProcessId(process);
    /*TODO: debug*/
    processLog(runTimeCommand, "Input Command");

    byte[] inputData = new byte[1024];
    String result = "";
    int numBytes;

    while ((numBytes = readInputStreamWithTimeout(processOutputStream, inputData, 1000)) > 0
        || !result.contains("srvrmgr>")) {
      if (numBytes > 0) result += new String(inputData, StandardCharsets.UTF_8);
      else {
        try {
          Thread.sleep(500);
        } catch (InterruptedException ex) {
        }
      }
      if (result.contains(("Fatal error"))) {
        this.process.destroy();
        throw new SrvrMgrException("Could not open connection to Siebel Gateway configuration");
      }
      //      System.out.println(result);
      inputData = new byte[1024];
    }
    /*TODO: debug*/
    processLog(result, "Output after process creation");
  }
Exemplo n.º 26
0
  private void spawnProcess() throws DCDError {
    GeneralCommandLine commandLine = new GeneralCommandLine(path);
    commandLine.setWorkDirectory(workingDirectory);
    commandLine.setRedirectErrorStream(true);
    ParametersList parametersList = commandLine.getParametersList();

    if (isNotNullOrEmpty(flags)) {
      List<String> importList = Arrays.asList(flags.split(","));
      for (String item : importList) {
        parametersList.addParametersString("-I");
        parametersList.addParametersString(item);
      }
    }

    try {
      process = commandLine.createProcess();
    } catch (ExecutionException e) {
      throw new InitError(e.toString());
    }
    input = new BufferedReader(new InputStreamReader(process.getInputStream()));
    output = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
  }
Exemplo n.º 27
0
  public static void main(String[] args) throws InterruptedException, IOException {
    final File INSTALLER = new File(args[0]);
    assert INSTALLER.exists();

    String directConsole = null;
    // windows specific
    if (isWindows()) {
      directConsole =
          INSTALLER.getName().contains("7.0.0")
              ? "-Dinstaller.direct.console=true"
              : "-Djline.WindowsTerminal.directConsole=false";
    }

    ProcessBuilder pb =
        new ProcessBuilder(
            buildArgs("java", directConsole, "-jar", INSTALLER.getAbsolutePath(), "-console"));
    pb.redirectErrorStream(true);

    // start process
    try {
      process = pb.start();
    } catch (IOException e) {
      System.err.println("Process failed to start.");
      System.exit(1);
    }

    // consume process input & error streams
    final InputStreamReader isr = new InputStreamReader(process.getInputStream());
    outPump = new CharPumper(isr);
    outPump.start();

    writer = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));

    waitFor("Please choose [0] :", "Failed to read the language dialogue.");
    sendLine("0");
    waitFor("press 1 to continue, 2 to quit, 3 to redisplay.", "Failed to read EULA");
    process.destroy();
  }
Exemplo n.º 28
0
 public static String getRecoveryMD5() {
   String MD5string = "";
   String recoveryFilename = "/dev/mtd/mtd1";
   try {
     Process p = Runtime.getRuntime().exec("su");
     OutputStream os = p.getOutputStream();
     os.write(("md5sum " + recoveryFilename).getBytes());
     os.flush();
     os.close();
     InputStream is = p.getInputStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(is));
     String str = br.readLine();
     MD5string = str.split("  ")[0].trim();
     is.close();
     br.close();
     p.destroy();
   } catch (Exception e) {
     Log.e(TAG, "Exception on getting Recovery MD5", e);
     return null;
   }
   Log.i(TAG, "Recovery MD5: " + MD5string);
   return MD5string;
 }
Exemplo n.º 29
0
  /**
   * This function is used to check if the java executable has the proper version.
   *
   * @param executable the path to the executable
   * @return {@code true} in case java meets the required specifications
   */
  private boolean isJavaExecutableWorking(@Nonnull final Path executable) {
    try {
      ProcessBuilder processBuilder = new ProcessBuilder(executable.toString(), "-version");
      processBuilder.redirectErrorStream(true);
      Process process = processBuilder.start();
      process.getOutputStream().close();

      try (BufferedReader reader =
          new BufferedReader(new InputStreamReader(process.getInputStream()))) {
        String line;
        while ((line = reader.readLine()) != null) {
          if (line.startsWith("java version")) {
            Matcher matcher = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)_(\\d+)").matcher(line);
            if (matcher.find()) {
              int mainVersion = Integer.parseInt(matcher.group(1));
              int majorVersion = Integer.parseInt(matcher.group(2));
              int minorVersion = Integer.parseInt(matcher.group(3));
              int buildNumber = Integer.parseInt(matcher.group(4));

              LOGGER.info(
                  "Matched Java version to {}.{}.{}_b{}",
                  mainVersion,
                  majorVersion,
                  minorVersion,
                  buildNumber);

              return mainVersion >= 1 && majorVersion >= 7 && buildNumber >= 21;
            }
          }
        }
      }
      process.destroy();
    } catch (IOException e) {
      LOGGER.error("Launching {} failed.", executable);
    }
    return false;
  }
Exemplo n.º 30
0
  public void run() {
    if (Thread.currentThread() == this) {
      Environment.setThreadEnvironment(launcherEnvironment);
      Job.setUserInterface(userInterface);
    }
    if (outStreamRedir instanceof OutputStreamChecker) {
      ((OutputStreamChecker) outStreamRedir).setExec(this);
    }
    if (errStreamRedir instanceof OutputStreamChecker) {
      ((OutputStreamChecker) errStreamRedir).setExec(this);
    }

    try {
      Runtime rt = Runtime.getRuntime();

      ExecProcessReader outReader = null;
      ExecProcessReader errReader = null;

      // run program
      synchronized (this) {
        try {
          if (command != null) p = rt.exec(command, envVars, dir);
          else p = rt.exec(exec, envVars, dir);
        } catch (IOException e) {
          System.out.println("Error running " + command + ": " + e.getMessage());
          return;
        }

        // eat output (stdout) and stderr from program so it doesn't block
        outReader = new ExecProcessReader(p.getInputStream(), outStreamRedir);
        errReader = new ExecProcessReader(p.getErrorStream(), errStreamRedir);
        outReader.start();
        errReader.start();

        // attach to input of process
        processWriter = new PrintWriter(p.getOutputStream());
      }

      // wait for exit status
      exitVal = p.waitFor();

      // also wait for redir threads to die, if doing redir
      if (outStreamRedir != null) outReader.join();
      if (errStreamRedir != null) errReader.join();

      StringBuffer com = new StringBuffer();
      if (command != null) com.append(command);
      else {
        for (int i = 0; i < exec.length; i++) com.append(exec[i] + " ");
      }

      // System.out.println("Process finished [exit: "+exitVal+"]: "+com.toString());
      synchronized (finishedListeners) {
        FinishedEvent e = new FinishedEvent(this, com.toString(), dir, exitVal);
        ArrayList<FinishedListener> copy = new ArrayList<FinishedListener>();
        // make copy cause listeners may want to remove themselves if process finished
        for (FinishedListener l : finishedListeners) {
          copy.add(l);
        }
        for (FinishedListener l : copy) {
          l.processFinished(e);
        }
      }

      synchronized (this) {
        if (processWriter != null) {
          processWriter.close();
          processWriter = null;
        }
      }

    } catch (Exception e) {
      ActivityLogger.logException(e);
    }
  }