Beispiel #1
1
 /**
  * Starts a native process on the server
  *
  * @param command the command to start the process
  * @param dir the dir in which the process starts
  */
 static String startProcess(String command, String dir) throws IOException {
   StringBuffer ret = new StringBuffer();
   String[] comm = new String[3];
   comm[0] = COMMAND_INTERPRETER[0];
   comm[1] = COMMAND_INTERPRETER[1];
   comm[2] = command;
   long start = System.currentTimeMillis();
   try {
     // Start process
     Process ls_proc = Runtime.getRuntime().exec(comm, null, new File(dir));
     // Get input and error streams
     BufferedInputStream ls_in = new BufferedInputStream(ls_proc.getInputStream());
     BufferedInputStream ls_err = new BufferedInputStream(ls_proc.getErrorStream());
     boolean end = false;
     while (!end) {
       int c = 0;
       while ((ls_err.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_err.read()));
       }
       c = 0;
       while ((ls_in.available() > 0) && (++c <= 1000)) {
         ret.append(conv2Html(ls_in.read()));
       }
       try {
         ls_proc.exitValue();
         // if the process has not finished, an exception is thrown
         // else
         while (ls_err.available() > 0) ret.append(conv2Html(ls_err.read()));
         while (ls_in.available() > 0) ret.append(conv2Html(ls_in.read()));
         end = true;
       } catch (IllegalThreadStateException ex) {
         // Process is running
       }
       // The process is not allowed to run longer than given time.
       if (System.currentTimeMillis() - start > MAX_PROCESS_RUNNING_TIME) {
         ls_proc.destroy();
         end = true;
         ret.append("!!!! Process has timed out, destroyed !!!!!");
       }
       try {
         Thread.sleep(50);
       } catch (InterruptedException ie) {
       }
     }
   } catch (IOException e) {
     ret.append("Error: " + e);
   }
   return ret.toString();
 }
  /**
   * Take a process, record its standard error and standard out streams, wait for it to finish
   *
   * @param process process to watch
   * @throws SecurityException if a security manager exists and its checkExec method doesn't allow
   *     creation of a sub process.
   * @throws IOException - if an I/O error occurs
   * @throws NullPointerException - if cmdarray is null
   * @throws IndexOutOfBoundsException - if cmdarray is an empty array (has length 0).
   * @since ostermillerutils 1.06.00
   */
  private ExecHelper(Process process, String charset) throws IOException {
    StringBuffer output = new StringBuffer();
    StringBuffer error = new StringBuffer();

    Reader stdout;
    Reader stderr;

    if (charset == null) {
      // This is one time that the system charset is appropriate,
      // don't specify a character set.
      stdout = new InputStreamReader(process.getInputStream());
      stderr = new InputStreamReader(process.getErrorStream());
    } else {
      stdout = new InputStreamReader(process.getInputStream(), charset);
      stderr = new InputStreamReader(process.getErrorStream(), charset);
    }
    char[] buffer = new char[1024];

    boolean done = false;
    boolean stdoutclosed = false;
    boolean stderrclosed = false;
    while (!done) {
      boolean readSomething = false;
      // read from the process's standard output
      if (!stdoutclosed && stdout.ready()) {
        readSomething = true;
        int read = stdout.read(buffer, 0, buffer.length);
        if (read < 0) {
          readSomething = true;
          stdoutclosed = true;
        } else if (read > 0) {
          readSomething = true;
          output.append(buffer, 0, read);
        }
      }
      // read from the process's standard error
      if (!stderrclosed && stderr.ready()) {
        int read = stderr.read(buffer, 0, buffer.length);
        if (read < 0) {
          readSomething = true;
          stderrclosed = true;
        } else if (read > 0) {
          readSomething = true;
          error.append(buffer, 0, read);
        }
      }
      // Check the exit status only we haven't read anything,
      // if something has been read, the process is obviously not dead yet.
      if (!readSomething) {
        try {
          this.status = process.exitValue();
          done = true;
        } catch (IllegalThreadStateException itx) {
          // Exit status not ready yet.
          // Give the process a little breathing room.
          try {
            Thread.sleep(100);
          } catch (InterruptedException ix) {
            process.destroy();
            throw new IOException("Interrupted - processes killed");
          }
        }
      }
    }

    this.output = output.toString();
    this.error = error.toString();
  }
Beispiel #3
0
  public static String getArchName() throws Exception {
    if (archName == null) {
      archName = "lin";

      // bits
      Process process = Runtime.getRuntime().exec("uname -m");
      process.waitFor();
      if (process.exitValue() != 0) throw new Exception("Error arch");
      BufferedReader inStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String arch = inStream.readLine();
      if (arch.equals("i686")) archName += "32";
      else archName += "64";
      process.destroy();

      // SSE
      process = Runtime.getRuntime().exec("cat /proc/cpuinfo");
      process.waitFor();
      if (process.exitValue() != 0) throw new Exception("Error /proc/cpuinfo");
      inStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String line, cpuinfo = "";
      while ((line = inStream.readLine()) != null) cpuinfo += line;

      String bestSSE = "sse";
      String[] sses = {"sse2", "sse3", "ssse3", "sse4", "avx"};
      for (int i = 0; i < sses.length; i++) {
        if (cpuinfo.indexOf(sses[i]) >= 0) bestSSE = sses[i];
      }
      archName += bestSSE;
      process.destroy();
    }
    return archName;
  }
Beispiel #4
0
 void doExitCommand() {
   File fp = new File(dataFile);
   boolean delete = fp.delete();
   pid.destroy();
   doResetCommand();
   setVisible(false);
 }
Beispiel #5
0
  // function to do the join use case
  public static void share() throws Exception {
    HttpPost method = new HttpPost(url + "/share");
    String ipAddress = null;

    Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
    while (en.hasMoreElements()) {
      NetworkInterface ni = (NetworkInterface) en.nextElement();
      if (ni.getName().equals("eth0")) {
        Enumeration<InetAddress> en2 = ni.getInetAddresses();
        while (en2.hasMoreElements()) {
          InetAddress ip = (InetAddress) en2.nextElement();
          if (ip instanceof Inet4Address) {
            ipAddress = ip.getHostAddress();
            break;
          }
        }
        break;
      }
    }

    method.setEntity(new StringEntity(username + ';' + ipAddress, "UTF-8"));
    try {
      ResponseHandler<String> responseHandler = new BasicResponseHandler();
      connIp = client.execute(method, responseHandler);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }

    // get present time
    date = new Date();
    long start = date.getTime();

    // Execute the vishwa share process
    Process p = Runtime.getRuntime().exec("java -jar vishwa/JVishwa.jar " + connIp);

    String ch = "alive";
    System.out.println("Type kill to unjoin from the grid");

    while (!ch.equals("kill")) {
      BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
      ch = in.readLine();
    }

    p.destroy();

    date = new Date();
    long end = date.getTime();
    long durationInt = end - start;

    String duration = String.valueOf(durationInt);
    method = new HttpPost(url + "/shareAck");
    method.setEntity(new StringEntity(username + ";" + duration, "UTF-8"));
    try {
      client.execute(method);
    } catch (IOException e) {
      System.err.println("Fatal transport error: " + e.getMessage());
      e.printStackTrace();
    }
  }
Beispiel #6
0
  void doExeCommand() {
    PSlider slider;
    Runtime program = Runtime.getRuntime();
    String currentCmd = new String();
    String X = new String();
    String Y = new String();

    // Kill the current executing program
    pid.destroy();

    // Setup the command parameters and run it
    slider = (PSlider) vSlider.elementAt(0);
    X = slider.getValue();
    slider = (PSlider) vSlider.elementAt(1);
    Y = slider.getValue();
    currentCmd = cmd + " " + X + " " + Y;

    try {
      pid = program.exec(currentCmd);
      if (isWindows == false) {
        Process pid2 = null;
        pid2 = program.exec("getpid WinSize");
      }
    } catch (IOException ie) {
      System.err.println("Couldn't run " + ie);
      System.exit(-1);
    }

    // Update the new value in the source code of the program
    doSourceFileUpdate();
    scrollPane.getViewport().setViewPosition(new Point(0, 20));
  }
  public static ArrayList<String> callSimString(String[] command) {

    ArrayList<String> result = new ArrayList<String>();

    try {

      // System.out.println("calling: "+command);

      ProcessBuilder processBuilder = new ProcessBuilder(command);

      Process p = processBuilder.start();

      p.waitFor();

      BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
      String line = "";
      while (((line = reader.readLine()) != null)) {
        result.add(line);
        System.out.println(line);
      }

      p.destroy();

    } catch (Exception exc) {
      System.out.println(exc.getMessage());
    }

    return result;
  }
  /** @see InputStream#close() */
  public void close() throws IOException {
    IOUtils.closeQuietly(processInputStream);
    IOUtils.closeQuietly(processOutputStream);

    if (process != null) {
      process.destroy();
    }
  }
Beispiel #9
0
 /**
  * Destroy given process.
  *
  * @param process
  */
 private void destroyProcess(Process process) {
   if (process != null) {
     try {
       process.destroy();
     } catch (Exception e) {
       log.trace("Error destroying process", e);
     }
   }
 }
Beispiel #10
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;
 }
Beispiel #11
0
  /** @param directory Directory where we list tags */
  @Override
  protected void buildTagList(File directory) {
    this.tagList = new TreeSet<TagEntry>();
    ArrayList<String> argv = new ArrayList<String>();
    ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
    argv.add(cmd);
    argv.add("tags");
    ProcessBuilder pb = new ProcessBuilder(argv);
    pb.directory(directory);
    Process process = null;
    BufferedReader in = null;

    try {
      process = pb.start();
      in = new BufferedReader(new InputStreamReader(process.getInputStream()));
      String line;
      while ((line = in.readLine()) != null) {
        String parts[] = line.split("  *");
        if (parts.length < 2) {
          throw new HistoryException("Tag line contains more than 2 columns: " + line);
        }
        // Grrr, how to parse tags with spaces inside?
        // This solution will loose multiple spaces;-/
        String tag = parts[0];
        for (int i = 1; i < parts.length - 1; ++i) {
          tag += " " + parts[i];
        }
        TagEntry tagEntry = new BazaarTagEntry(Integer.parseInt(parts[parts.length - 1]), tag);
        // Bazaar lists multiple tags on more lines. We need to merge those into single TagEntry
        TagEntry higher = this.tagList.ceiling(tagEntry);
        if (higher != null && higher.equals(tagEntry)) {
          // Found in the tree, merge tags
          this.tagList.remove(higher);
          tagEntry.setTags(higher.getTags() + ", " + tag);
        }
        this.tagList.add(tagEntry);
      }
    } catch (IOException e) {
      OpenGrokLogger.getLogger().log(Level.WARNING, "Failed to read tag list: {0}", e.getMessage());
      this.tagList = null;
    } catch (HistoryException e) {
      OpenGrokLogger.getLogger()
          .log(Level.WARNING, "Failed to parse tag list: {0}", e.getMessage());
      this.tagList = null;
    }

    IOUtils.close(in);
    if (process != null) {
      try {
        process.exitValue();
      } catch (IllegalThreadStateException e) {
        // the process is still running??? just kill it..
        process.destroy();
      }
    }
  }
Beispiel #12
0
 /** Calls ipconfig and parses the result to find servers and a search path. */
 private static void findNT() {
   try {
     Process p;
     p = Runtime.getRuntime().exec("ipconfig /all");
     findWin(p.getInputStream());
     p.destroy();
   } catch (Exception e) {
     return;
   }
 }
Beispiel #13
0
 public static String getCCName() throws Exception {
   if (ccName == null) {
     Process process = Runtime.getRuntime().exec("gcc -dumpversion");
     process.waitFor();
     if (process.exitValue() != 0) throw new Exception("Error gcc -dumpversion");
     BufferedReader inStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
     String[] list = inStream.readLine().split("\\.");
     ccName = "gcc" + list[0] + list[1] + "-mt";
     process.destroy();
   }
   return ccName;
 }
  public synchronized void close() throws IOException {
    if (myWaitForThreadFuture != null) {
      myWaitForThreadFuture.cancel(true);
    }
    if (myWaitSemaphore != null) {
      myWaitSemaphore.up();
    }

    try {
      if (myInputStream != null && !myContainsError) {
        myInputStream.close();
        try {
          Thread.sleep(10);
        } catch (InterruptedException e) {
          // ignore
        }
      }
    } finally {
      try {
        if (myOutputStream != null && !myContainsError) {
          myOutputStream.close();
          try {
            Thread.sleep(10);
          } catch (InterruptedException e) {
            // ignore
          }
        }
        try {
          if (myErrThread != null) {
            myErrThread.setProcessTerminated(true);
          }
          if (myStdErrFuture != null) {
            myStdErrFuture.get();
          }
        } catch (InterruptedException e) {
          //
        } catch (ExecutionException e) {
          LOG.error(e);
        }
      } finally {
        try {
          if (myProcess != null) {
            myProcess.destroy();
          }
        } finally {
          myInputStream = null;
          myOutputStream = null;
          myProcess = null;
        }
      }
    }
  }
Beispiel #15
0
 public void disposeVM() {
   try {
     if (vm != null) {
       vm.dispose();
       vm = null;
     }
   } finally {
     if (process != null) {
       process.destroy();
       process = null;
     }
     waitOutputComplete();
   }
 }
Beispiel #16
0
  public static void exit() {
    writeInS3270(WrapperCodes.click(3), false); // Exit
    writeInS3270(WrapperCodes.ENTER, false);
    writeInS3270(WrapperCodes.ENTER, false);

    try {
      writeInS3270(WrapperCodes.DISCONNECT, false);
      read.close();
      write.close();
      s3270.destroy();
    } catch (IOException e) {
      System.err.println(e);
    }
    System.exit(0);
  }
  public static void main(String[] args) throws Exception {
    int counter = 0;
    while (true) {
      Thread outThread = null;
      Thread errThread = null;
      try {
        // org.pitest.mutationtest.instrument.MutationTestUnit#runTestInSeperateProcessForMutationRange

        // *** start slave

        ServerSocket commSocket = new ServerSocket(0);
        int commPort = commSocket.getLocalPort();
        System.out.println("commPort = " + commPort);

        // org.pitest.mutationtest.execute.MutationTestProcess#start
        //   - org.pitest.util.CommunicationThread#start
        FutureTask<Integer> commFuture = createFuture(commSocket);
        //   - org.pitest.util.WrappingProcess#start
        //       - org.pitest.util.JavaProcess#launch
        Process slaveProcess = startSlaveProcess(commPort);
        outThread = new Thread(new ReadFromInputStream(slaveProcess.getInputStream()), "stdout");
        errThread = new Thread(new ReadFromInputStream(slaveProcess.getErrorStream()), "stderr");
        outThread.start();
        errThread.start();

        // *** wait for slave to die

        // org.pitest.mutationtest.execute.MutationTestProcess#waitToDie
        //    - org.pitest.util.CommunicationThread#waitToFinish
        System.out.println("waitToFinish");
        Integer controlReturned = commFuture.get();
        System.out.println("controlReturned = " + controlReturned);
        // NOTE: the following won't get called if commFuture.get() fails!
        //    - org.pitest.util.JavaProcess#destroy
        outThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        errThread.interrupt(); // org.pitest.util.AbstractMonitor#requestStop
        slaveProcess.destroy();
      } catch (Exception e) {
        e.printStackTrace(System.out);
      }

      // test: the threads should exit eventually
      outThread.join();
      errThread.join();
      counter++;
      System.out.println("try " + counter + ": stdout and stderr threads exited normally");
    }
  }
Beispiel #18
0
 /** Kills the existing process and closes input and output if they exist. */
 private synchronized void kill() {
   if (process != null) process.destroy();
   process = null;
   try {
     if (input != null) input.close();
   } catch (IOException e) {
     /* Ignored */
   }
   input = null;
   try {
     if (output != null) output.close();
   } catch (IOException e) {
     /* Ignored */
   }
   output = null;
 }
  /** Finishes debugger. */
  public void finishDebugger() throws DebuggerException {
    threadGroup.setRemoteThreadGroup(null);
    if (remoteDebugger != null) {
      remoteDebugger.close();
      remoteDebugger = null;
    }
    if (process != null) process.destroy();
    if (debuggerThread != null) {
      debuggerThread.interrupt();
      debuggerThread.stop();
    }

    super.finishDebugger();

    synchronizer = null;
  }
    // Kills the JVM process and any active threads on it.
    private void kill() {
      if (redirectErr != null) {
        redirectErr.close();
        redirectErr.interrupt();
      }

      if (redirectOut != null) {
        redirectOut.close();
        redirectOut.interrupt();
      }

      if (JVM != null) {
        JVM.destroy();
        JVM = null;
      }

      JVMrunning = false;
    }
Beispiel #21
0
  @Override
  public InputStream getHistoryGet(String parent, String basename, String rev) {
    InputStream ret = null;

    File directory = new File(directoryName);

    Process process = null;
    try {
      String filename =
          (new File(parent, basename)).getCanonicalPath().substring(directoryName.length() + 1);
      ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK);
      String argv[] = {cmd, "cat", "-r", rev, filename};
      process = Runtime.getRuntime().exec(argv, null, directory);

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      byte[] buffer = new byte[32 * 1024];
      InputStream in = process.getInputStream();
      int len;

      while ((len = in.read(buffer)) != -1) {
        if (len > 0) {
          out.write(buffer, 0, len);
        }
      }

      ret = new ByteArrayInputStream(out.toByteArray());
    } catch (Exception exp) {
      OpenGrokLogger.getLogger()
          .log(Level.SEVERE, "Failed to get history: " + exp.getClass().toString(), exp);
    } finally {
      // Clean up zombie-processes...
      if (process != null) {
        try {
          process.exitValue();
        } catch (IllegalThreadStateException exp) {
          // the process is still running??? just kill it..
          process.destroy();
        }
      }
    }

    return ret;
  }
Beispiel #22
0
    // Kills the JVM process and any active threads on it.
    private void kill() {
      if (redirectErr != null) {
        redirectErr.close();
        redirectErr.interrupt();
      }

      if (redirectOut != null) {
        redirectOut.close();
        redirectOut.interrupt();
      }

      if (JVM != null) {
        JVM.destroy();
        JVM = null;
      }

      JVMrunning = false;

      println("JVM reset on " + java.util.Calendar.getInstance().getTime().toString(), progErr);
    }
Beispiel #23
0
 /** Get command output string. */
 public static String getCMDOutputString(String[] args) {
   try {
     ProcessBuilder cmd = new ProcessBuilder(args);
     Process process = cmd.start();
     InputStream in = process.getInputStream();
     StringBuilder sb = new StringBuilder();
     byte[] re = new byte[64];
     int len;
     while ((len = in.read(re)) != -1) {
       sb.append(new String(re, 0, len));
     }
     in.close();
     process.destroy();
     if (Log.isPrint) {
       Log.i(TAG, "CMD: " + sb.toString());
     }
     return sb.toString();
   } catch (IOException ex) {
     ex.printStackTrace();
   }
   return null;
 }
  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();
  }
Beispiel #25
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;
 }
Beispiel #26
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;
  }
 /**
  * Closes down connections to the underlying process. This method will be used only if the
  * supporting Java Native Interface library could not be loaded.
  */
 private synchronized void pure_close(PrintStream out) {
   /*
    * Try to close this process for at least 30 seconds.
    */
   for (int i = 0; i < 30; i++) {
     try {
       in.close();
       err.close();
       out.flush();
       out.close();
     } catch (IOException ioe) {
     }
     try {
       exit_code = p.waitFor();
       p.destroy();
       break;
     } catch (InterruptedException ie) {
     }
     try {
       Thread.sleep(1000);
     } catch (InterruptedException ie) {
     }
   }
 }
Beispiel #28
0
  public static int executeCommand(String completeCommand, PrintWriter out) {
    try {
      Process p = Runtime.getRuntime().exec(completeCommand);
      if (out != null) {
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = in.readLine();
        while (line != null) {
          out.println(line);
          line = in.readLine();
        }
        in.close();
        out.flush();
      }
      p.waitFor();
      int status = p.exitValue();
      p.destroy();
      return status;

    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
      return -1;
    }
  }
Beispiel #29
0
 /** End this process, if it is running. Otherwise, does nothing */
 public synchronized void destroyProcess() {
   if (p != null) {
     p.destroy();
   }
 }
  private void killLogstashAgent(int logAgentNumber, String logstashLogPath) {

    FileObject listendir;
    CustomFileListener listener = new CustomFileListener();
    long TIMEOUT_BETWEEN_FILE_QUERYING = 1000;
    long LOOP_TIMEOUT_IN_MILLIS = 10 * 1000;

    try {
      FileSystemManager fileSystemManager = VFS.getManager();
      listendir = fileSystemManager.resolveFile(logstashLogPath);
    } catch (FileSystemException e) {
      e.printStackTrace();
      return;
    }

    DefaultFileMonitor fm = new DefaultFileMonitor(listener);
    fm.setRecursive(true);
    fm.addFile(listendir);
    fm.setDelay(TIMEOUT_BETWEEN_FILE_QUERYING);
    fm.start();

    LogUtils.log("waiting to destroy logger");
    long startTimeMillis = System.currentTimeMillis();

    while (true) {

      if (!listener.isProcessUp()) {
        break;
      }

      listener.setProcessUp(false);

      try {
        TimeUnit.MILLISECONDS.sleep(LOOP_TIMEOUT_IN_MILLIS);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    long endTimeMillis = System.currentTimeMillis();
    LogUtils.log("destroying logstash agent " + logAgentNumber);
    LogUtils.log("waited " + (endTimeMillis - startTimeMillis) / 1000 + " seconds");
    fm.stop();

    //        File logstashOutputFile = new File(logstashLogPath);

    if (logAgentNumber == 1) {

      process.destroy();
      process = null;
    } else {

      process2.destroy();
      process2 = null;
    }

    //        try {
    //            TimeUnit.SECONDS.sleep(5);
    //
    //            LogUtils.log("returning logstash config file to initial state");
    //            if(logAgentNumber == 1){
    //                IOUtils.replaceFileWithMove(new File(confFilePath), new File(backupFilePath));
    //                FileUtils.deleteQuietly(new File(backupFilePath));
    //            }
    //            else{
    //                IOUtils.replaceFileWithMove(new File(confFilePath2), new
    // File(backupFilePath2));
    //                FileUtils.deleteQuietly(new File(backupFilePath2));
    //
    //            }
    //        } catch (IOException e) {
    //            e.printStackTrace();
    //        } catch (InterruptedException e) {
    //            e.printStackTrace();
    //        }

    //        if(logstashOutputFile.exists()){
    //            FileUtils.deleteQuietly(logstashOutputFile);
    //        }
  }