예제 #1
0
 @Before
 public void setUp() {
   processManager =
       new ProcessManager() {
         @Override
         Process startProcess(ProcessBuilder processBuilder, String msgCommandInfo) {
           return processStartedByManager;
         }
       };
   processStartedByManager = mock(Process.class);
   when(processStartedByManager.getInputStream()).thenReturn(mock(InputStream.class));
   when(processStartedByManager.getErrorStream()).thenReturn(mock(InputStream.class));
   when(processStartedByManager.getOutputStream()).thenReturn(mock(OutputStream.class));
   processOne = mock(Process.class);
   processTwo = mock(Process.class);
   when(processOne.getInputStream()).thenReturn(mock(InputStream.class));
   when(processOne.getErrorStream()).thenReturn(mock(InputStream.class));
   when(processOne.getOutputStream()).thenReturn(mock(OutputStream.class));
   when(processOne.exitValue()).thenThrow(new IllegalStateException());
   when(processTwo.exitValue()).thenThrow(new IllegalStateException());
   when(processTwo.getInputStream()).thenReturn(mock(InputStream.class));
   when(processTwo.getErrorStream()).thenReturn(mock(InputStream.class));
   when(processTwo.getOutputStream()).thenReturn(mock(OutputStream.class));
   ConcurrentMap<Process, ProcessWrapper> processMap = processManager.getProcessMap();
   wrapperForProcessOne =
       new ProcessWrapper(processOne, "tag1", null, inMemoryConsumer(), null, "ERROR: ");
   processMap.put(processOne, wrapperForProcessOne);
   wrapperForProcessTwo =
       new ProcessWrapper(processTwo, "tag2", null, inMemoryConsumer(), null, "ERROR: ");
   processMap.put(processTwo, wrapperForProcessTwo);
 }
예제 #2
0
파일: Library.java 프로젝트: jfellus/agem
  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;
  }
  /**
   * Calls the Unix sort command with the options <code>$filesNames -o
   * $outputfile -T WaybackSettings#WAYBACK_AGGREGATOR_TEMP_DIR.
   *
   * Sets the LC_ALL environment variable before making the call.
   *
   * @param files The files to merge and sort
   * @param outputFile The resulting sorted file
   * @param additionalArgs A list af extra arguments, which (if different from
   *                       null) are added to the sort call.<p> Note: If any
   *                       of the args contain a whitespace the call will
   *                       fail.
   */
  private void processFiles(File[] files, File outputFile, List<String> additionalArgs) {
    if (files.length == 0) {
      // Empty file list will cause sort to wait for further input,
      // and the call will therefore never return
      return;
    }

    Process p = null;

    try {
      List<String> inputFileList = new LinkedList<String>();
      for (int i = 0; i < files.length; i++) {
        if (files[i].exists() && files[i].isFile()) {
          inputFileList.add(files[i].getCanonicalPath());
        } else {
          log.warn(
              "File "
                  + files[i]
                  + " doesn't exist or isn't a regular file, "
                  + "dropping from list of files to "
                  + "sort and merge");
        }
      }
      List<String> cmd = new LinkedList<String>();
      // Prepare to run the unix sort command, see sort manual page for
      // details
      cmd.add("sort");
      cmd.addAll(inputFileList);
      cmd.add("-o");
      cmd.add(outputFile.getCanonicalPath());
      cmd.add("-T");
      cmd.add(Settings.get(WaybackSettings.WAYBACK_AGGREGATOR_TEMP_DIR));
      if (additionalArgs != null && !additionalArgs.isEmpty()) {
        for (String argument : additionalArgs) {
          ArgumentNotValid.checkTrue(
              argument.indexOf(' ') == -1,
              "The argument '" + argument + "' contains spaces, this isn't allowed ");
        }
        cmd.addAll(additionalArgs);
      }
      ProcessBuilder pb = new ProcessBuilder(cmd);
      // Reset all locale definitions
      pb.environment().put("LC_ALL", "C");
      // Run the command in the user.dir directory
      pb.directory(new File(System.getProperty("user.dir")));
      p = pb.start();
      p.waitFor();
      if (p.exitValue() != 0) {
        log.error("Failed to sort index files, sort exited with " + "return code " + p.exitValue());
      }
    } catch (Exception e) {
      log.error("Failed to aggregate indexes ", e);
    }
  }
예제 #4
0
 private int executeGraphviz(
     File inputFile, String layoutAlgorithm, String outputFormat, File outputFile)
     throws IOException, InterruptedException {
   FileUtils.checkFile(inputFile);
   FileUtils.checkDirectory(outputFile.getParent());
   String command =
       "dot -K" + layoutAlgorithm + " -T" + outputFormat + " -o" + outputFile + " " + inputFile;
   logger.debug("Graphviz command line: " + command);
   Process process = Runtime.getRuntime().exec(command);
   process.waitFor();
   logger.debug("Graphviz exit status: " + process.exitValue());
   return process.exitValue();
 }
예제 #5
0
 public static int exec(String cmd) throws IOException, InterruptedException {
   System.out.println(cmd);
   Runtime rt = Runtime.getRuntime();
   Process p = rt.exec(cmd.split(" "));
   p.waitFor();
   BufferedReader out = new BufferedReader(new InputStreamReader(p.getInputStream()));
   String line = null;
   while ((line = out.readLine()) != null) {
     System.out.println(line);
   }
   System.out.println(p.exitValue());
   return p.exitValue();
 }
 public void listen() {
   mRunning = true;
   String[] command = new String[] {"logcat", "-v", "long"};
   try {
     mLogCatProcess = Runtime.getRuntime().exec(command);
     BufferedReader reader =
         new BufferedReader(new InputStreamReader(mLogCatProcess.getInputStream()));
     // Discard first line, it's just a header
     reader.readLine();
     for (LogEntry entry = readLogEntry(reader); !mStopped; entry = readLogEntry(reader)) {
       if (entry == null) {
         try {
           mLogCatProcess.exitValue();
           break;
         } catch (IllegalThreadStateException e) {
           // Still running, we just got a bad message
           continue;
         }
       }
       for (LogCatListener listener : mListeners) {
         listener.handleLogCatMessage(entry);
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   mRunning = false;
   Log.i(getClass().getName(), "Stopped Listening.");
 }
예제 #7
0
 public Integer getExitCode() {
   try {
     return process.exitValue();
   } catch (IllegalThreadStateException exception) {
     return null;
   }
 }
예제 #8
0
 public int status() {
   try {
     return proc.exitValue();
   } catch (IllegalThreadStateException itse) {
     return STILL_RUNNING;
   }
 }
예제 #9
0
  public static String getSDCardPath() {
    String cmd = "cat /proc/mounts";
    Runtime run = Runtime.getRuntime(); // 返回与当前 Java 应用程序相关的运行时对象
    try {
      Process p = run.exec(cmd); // 启动另一个进程来执行命令
      BufferedInputStream in = new BufferedInputStream(p.getInputStream());
      BufferedReader inBr = new BufferedReader(new InputStreamReader(in));

      String lineStr;
      while ((lineStr = inBr.readLine()) != null) {
        // 获得命令执行后在控制台的输出信息
        //	            	Log.i("CommonUtil:getSDCardPath", lineStr);
        if (lineStr.contains("sdcard") && lineStr.contains(".android_secure")) {
          String[] strArray = lineStr.split(" ");
          if (strArray != null && strArray.length >= 5) {
            String result = strArray[1].replace("/.android_secure", "");
            return result;
          }
        }
        // 检查命令是否执行失败。
        if (p.waitFor() != 0 && p.exitValue() == 1) {
          // p.exitValue()==0表示正常结束,1:非正常结束
          Log.e("CommonUtil:getSDCardPath", "命令执行失败!");
        }
      }
      inBr.close();
      in.close();
    } catch (Exception e) {
      //	            Log.e("CommonUtil:getSDCardPath", e.toString());

      return Environment.getExternalStorageDirectory().getPath();
    }

    return Environment.getExternalStorageDirectory().getPath();
  }
예제 #10
0
  /**
   * Change local file's permission.
   *
   * @param filePath that will change permission
   * @param perms the permission, e.g. "775"
   * @throws IOException
   */
  public static void changeLocalFilePermission(String filePath, String perms) throws IOException {
    // TODO switch to java's Files.setPosixFilePermissions() if java 6 support is dropped
    List<String> commands = new ArrayList<String>();
    commands.add("/bin/chmod");
    commands.add(perms);
    File file = new File(filePath);
    commands.add(file.getAbsolutePath());

    try {
      ProcessBuilder builder = new ProcessBuilder(commands);
      Process process = builder.start();

      process.waitFor();

      redirectIO(process);

      if (process.exitValue() != 0) {
        throw new IOException(
            "Can not change the file " + file.getAbsolutePath() + " 's permission to be " + perms);
      }
    } catch (InterruptedException e) {
      LOG.error(e.getMessage());
      throw new IOException(e);
    }
  }
예제 #11
0
  @Override
  public void run() {

    if (clientIP.length() > 0) {
      Integer portTo =
          Integer.parseInt(JRadiusConfigurator.getInstance().getProperty("send2ip_port"));

      if (JRadiusConfigurator.getInstance().getProperty("send_by_self").equals("enabled")) {

        Socket toServer;
        try {
          toServer = new Socket(clientIP, portTo);
          OutputStream serverOut = new BufferedOutputStream(toServer.getOutputStream());
          serverOut.write(message.getBytes());
          toServer.close();
        } catch (UnknownHostException e) {
          logger.error("Send2ip Unknown host error: " + e.getMessage());
        } catch (IOException e) {
          logger.error("Send2ip error: " + e.getMessage());
        }
      } else {
        try {
          String execStr = JRadiusConfigurator.getInstance().getProperty("send_program");
          execStr = String.format(execStr + " %s %s '%s'", clientIP, portTo, message);
          Process p = Runtime.getRuntime().exec(execStr);
          p.waitFor();
          logger.info("Execute send2ip program result: " + p.exitValue());
        } catch (Exception e) {
          logger.error("Error executing send2ip program: " + e.getMessage());
        }
      }
    }
  }
 /**
  * Attempts to open a url with the specified browser. This is a utility method called by the
  * openUrl methods.
  *
  * @param winBrowser WindowsBrowser
  * @param protocol String
  * @param urlString String
  * @return boolean
  * @throws BrowserLaunchingExecutionException
  */
 private boolean openUrlWithBrowser(WindowsBrowser winBrowser, String protocol, String urlString)
     throws BrowserLaunchingExecutionException {
   boolean success = false;
   try {
     logger.info(winBrowser.getBrowserDisplayName());
     logger.info(urlString);
     logger.info(protocol);
     String args = getCommandArgs(protocol, winBrowser, urlString, forceNewWindow);
     if (logger.isDebugEnabled()) {
       logger.debug(args);
     }
     Process process = Runtime.getRuntime().exec(args);
     // This avoids a memory leak on some versions of Java on Windows.
     // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
     process.waitFor();
     // some browsers (mozilla, firefox) return 1 if you attempt to
     // open a url and an instance of that browser is already running
     // not clear why because the call is succeeding, ie the browser
     // opens the url.
     // If we don't say 1 is also a success, we get two browser
     // windows or tabs opened to the url.
     //
     // We could make this check smarter in the future if we run
     // into problems. the winBrowser object could handle the
     // check to make it browser specific.
     int exitValue = process.exitValue();
     success = exitValue == 0 || exitValue == 1;
   }
   // Runtimes may throw InterruptedException
   // want to catch every possible exception and wrap it
   catch (Exception e) {
     throw new BrowserLaunchingExecutionException(e);
   }
   return success;
 }
예제 #13
0
  /** Run thread */
  private void startRead() {
    // While to end
    while (true) {
      try {
        mProcess.exitValue();
        // read last
        read();
        break;
      } catch (IllegalThreadStateException e) {
        read();
      }
      Tools.sleepIgnoreInterrupt(50);
    }

    // Read end
    int len;
    if (mInStream != null) {
      try {
        while (true) {
          len = mInStream.read(BUFFER);
          if (len <= 0) break;
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // Close destroy and done the read
    close();
    destroy();

    isDone = true;
  }
예제 #14
0
 public int exitValue() {
   if (stillRunning()) {
     return NO_EXIT_VALUE;
   } else {
     return _task.exitValue();
   }
 }
예제 #15
0
 /**
  * @param command run a command from a list usually space are used as splitter
  * @return output buffered at index 0 and error buffered at index 1
  * @throws IOException if error while trying to command output
  */
 public static List<BufferedReader> run(final List<String> command) throws Exception {
   final Process process = new ProcessBuilder(command).start();
   final InputStream out = process.getInputStream();
   final InputStreamReader outr = new InputStreamReader(out, "UTF-8");
   final BufferedReader outb = new BufferedReader(outr);
   final InputStream err = process.getErrorStream();
   final InputStreamReader errr = new InputStreamReader(err, "UTF-8");
   final BufferedReader errbr = new BufferedReader(errr);
   synchronized (process) {
     try {
       process.waitFor();
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
   int exitStatus = process.exitValue();
   if (exitStatus != 0) {
     final StringBuilder msg = new StringBuilder();
     errbr
         .lines()
         .forEach(
             line -> {
               msg.append(line);
             });
     throw new Exception(msg.toString());
   }
   return Arrays.asList(outb, errbr);
 }
예제 #16
0
  private int _executeBashCommands(List<String> commands, String targetSlave)
      throws InterruptedException, IOException {

    StringBuffer sb = new StringBuffer("ssh ");

    sb.append(targetSlave);
    sb.append(" '");

    if ((_cleanUpCommand != null) && !_cleanUpCommand.isEmpty()) {
      sb.append(_cleanUpCommand);
      sb.append("; ");
    }

    for (int i = 0; i < commands.size(); i++) {
      sb.append(commands.get(i));

      if (i < (commands.size() - 1)) {
        sb.append(" && ");
      }
    }

    sb.append("'");

    Process process = JenkinsResultsParserUtil.executeBashCommands(sb.toString());

    return process.exitValue();
  }
예제 #17
0
  public void checkVersion() {
    int retVal = 0;
    try {
      String testProgram = System.getProperty("cli_test_program");
      if (testProgram == null || testProgram.length() == 0)
        failed("Check the make file. Java must be called with -Dcli_ure_test=pathtoexe");
      String unoPath = System.getProperty("path");
      if (unoPath == null || unoPath.length() == 0)
        failed("Check the make file. Java must be called with -Duno_path=path_to_ure_bin_folder");
      String sSystemRoot = System.getProperty("SystemRoot");
      if (sSystemRoot == null || sSystemRoot.length() == 0)
        failed("Check the make file. Java  must be called with -DSystemRoot=%SystemRoot%.");

      // We need to set the PATH because otherwise it appears that runtests inherits the PATH
      // from build environment. Then the bootstrapping fails because the libraries
      // are not used from the office.
      // .NET 2 requires SystemRoot being set.
      String[] arEnv = new String[] {"PATH=" + unoPath, "SystemRoot=" + sSystemRoot};
      Process proc = null;

      proc = Runtime.getRuntime().exec(testProgram, arEnv);
      new Reader(proc.getInputStream());
      new Reader(proc.getErrorStream());
      proc.waitFor();
      retVal = proc.exitValue();
    } catch (Exception e) {
      e.printStackTrace();
      System.out.println(e.getMessage());
      failed("Unexpected exception.");
    }
    if (retVal != 0) failed("Tests for library versioning failed.");
  }
  @Override
  public void stop() {
    stopping = true;
    try {
      // A newline is interpreted by the replica client as a sign to stop.
      os.write('\n');
      os.flush();
    } catch (IOException e) {
      process.destroy();
    }

    try {
      Thread.sleep(100);
    } catch (InterruptedException e) {
      e.printStackTrace();
      flushFileOut();
      System.exit(1);
    }

    try {
      process.exitValue();
    } catch (IllegalThreadStateException e) {
      process.destroy();
    }

    flushFileOut();
  }
예제 #19
0
  /** Executes the Build War script. */
  private File execBuildWar(final File sonarBaseDir) {
    File sonarWar = new File(sonarBaseDir, "war/sonar.war");
    if (sonarWar.exists()) {
      return sonarWar;
    }

    File script = getBuildSonarScript(sonarBaseDir);
    new File(sonarBaseDir, "war/apache-ant-1.7.0/bin/ant").setExecutable(true);
    new File(sonarBaseDir, "war/apache-ant-1.7.0/bin/ant.bat").setExecutable(true);
    try {
      Process p =
          Runtime.getRuntime().exec(script.getAbsolutePath(), null, new File(sonarBaseDir, "war"));
      InputStream is = p.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);
      String line;

      while ((line = br.readLine()) != null) {
        LOGGER.info(line);
      }

      p.waitFor();
      LOGGER.info(String.valueOf(p.exitValue()));

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

    return sonarWar;
  }
예제 #20
0
  public static int runProcess(String[] pstr, int timeout)
      throws TimeoutException, InterruptedException, IOException {

    String cmdStr = "";
    for (String st : pstr) {
      cmdStr = cmdStr + " " + st;
    }
    SDFSLogger.getLog().debug("Executing [" + cmdStr + "]");
    Process p = null;
    try {
      p = Runtime.getRuntime().exec(pstr, null, new File(Main.volume.getPath()));
      ReadStream s1 = new ReadStream("stdin", p.getInputStream());
      ReadStream s2 = new ReadStream("stderr", p.getErrorStream());
      s1.start();
      s2.start();
    } catch (Throwable e) {
      SDFSLogger.getLog().error("unable to execute " + cmdStr, e);
      throw new IOException(e);
    }
    long now = System.currentTimeMillis();
    long finish = now + timeout;
    while (isAlive(p) && (System.currentTimeMillis() < finish)) {
      Thread.sleep(10);
    }
    if (isAlive(p)) {
      throw new TimeoutException("Process [" + cmdStr + "] timeout out after [" + timeout + "] ms");
    }
    return p.exitValue();
  }
예제 #21
0
  private static void errorHandler(
      Process startClientProcess, BufferedReader stdErr, BufferedReader stdOut, StringBuilder err) {
    try {
      if (startClientProcess.exitValue() != 0) {
        String s;
        while ((s = stdErr.readLine()) != null) {
          err.append(s);
        }
        stdErr.close();
        stdOut.close();

        logger.error("failed to make filesystem \n" + err);
        throw new RuntimeException();
      } else {
        String s = "";
        while ((s = stdErr.readLine()) != null) {
          err.append(s);
        }
        while ((s = stdOut.readLine()) != null) {
          err.append(s);
        }
        stdErr.close();
        stdOut.close();
        if (err.length() != 0) {

          logger.error("failed to make filesystem \n" + err);
          throw new RuntimeException();
        }
      }

    } catch (final IOException e) {
      throw new RuntimeException(e);
    }
  }
    @Override
    public void run() {
      try {
        process = startProcess();
        // consoleOutput = getConsoleOutput(process);
      } catch (IOException e) {
        throw prepareException(e);
      } finally {
        processIsReady.countDown();
      }

      try {
        process.waitFor();
        if (process.exitValue() != 0) {
          LOGGER.info(
              "Mongos ["
                  + mongosPath
                  + PORT_ARGUMENT_NAME
                  + port
                  + LOGPATH_ARGUMENT_NAME
                  + logRelativePath
                  + "] console output is: "
                  + consoleOutput);
        }
      } catch (InterruptedException ie) {
        throw prepareException(ie);
      }
    }
 /**
  * Opens a url using the default browser.
  *
  * @param urlString String
  * @throws UnsupportedOperatingSystemException
  * @throws BrowserLaunchingExecutionException
  * @throws BrowserLaunchingInitializingException
  */
 public void openUrl(String urlString)
     throws UnsupportedOperatingSystemException, BrowserLaunchingExecutionException,
         BrowserLaunchingInitializingException {
   try {
     logger.info(urlString);
     String protocol = getProtocol(urlString);
     logger.info(protocol);
     // try the system prop first
     boolean successfullSystemPropLaunch = false;
     String browserName = System.getProperty(IBrowserLaunching.BROWSER_SYSTEM_PROPERTY, null);
     if (browserName != null) {
       Map browserMap = getBrowserMap();
       WindowsBrowser winBrowser = (WindowsBrowser) browserMap.get(browserName);
       if (winBrowser != null) {
         logger.debug("using browser from system property");
         successfullSystemPropLaunch = openUrlWithBrowser(winBrowser, protocol, urlString);
       }
     }
     if (!successfullSystemPropLaunch) {
       String[] args = getCommandArgs(protocol, urlString);
       if (logger.isDebugEnabled()) {
         logger.debug(getArrayAsString(args));
       }
       Process process = Runtime.getRuntime().exec(args);
       // This avoids a memory leak on some versions of Java on Windows.
       // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
       process.waitFor();
       process.exitValue();
     }
   } catch (Exception e) {
     logger.error("fatal exception", e);
     throw new BrowserLaunchingExecutionException(e);
   }
 }
예제 #24
0
  private static boolean startProcess(String command, File directory, final CharCallback callback) {
    try {
      final Process process =
          new ProcessBuilder(command.split(" "))
              .redirectErrorStream(true)
              .directory(directory)
              .start();

      Thread t =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  BufferedReader reader =
                      new BufferedReader(new InputStreamReader(process.getInputStream()), 1);
                  try {
                    int c = 0;
                    while ((c = reader.read()) != -1) {
                      callback.character((char) c);
                    }
                  } catch (IOException e) {
                    //						e.printStackTrace();
                  }
                }
              });
      t.setDaemon(true);
      t.start();
      process.waitFor();
      t.interrupt();
      return process.exitValue() == 0;
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }
  }
예제 #25
0
파일: Ctags.java 프로젝트: jclulow/opengrok
  public Definitions doCtags(String file) throws IOException {
    boolean ctagsRunning = false;
    if (ctags != null) {
      try {
        ctags.exitValue();
        ctagsRunning = false;
        // ctags is dead! we must restart!!!
      } catch (IllegalThreadStateException exp) {
        ctagsRunning = true;
        // ctags is still running :)
      }
    }

    if (!ctagsRunning) {
      initialize();
    }

    Definitions ret = null;
    if (file.length() > 0 && !"\n".equals(file)) {
      // log.fine("doing >" + file + "<");
      ctagsIn.write(file);
      ctagsIn.flush();
      ret = new Definitions();
      readTags(ret);
    }

    return ret;
  }
예제 #26
0
  public static int execCmd(String cmd) throws Exception {
    int result = -1;
    try {
      Process p = Runtime.getRuntime().exec(cmd);
      p.waitFor();
      // for test
      StringBuilder sucMsg = new StringBuilder();
      StringBuilder errMsg = new StringBuilder();
      BufferedReader sucReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
      BufferedReader errReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
      String tmp;
      boolean bHasError = false;
      while ((tmp = sucReader.readLine()) != null) {
        sucMsg.append(tmp);
      }
      while ((tmp = errReader.readLine()) != null) {
        errMsg.append(tmp);
        if (!tmp.equals("")) {
          bHasError = true;
        }
      }

      result = p.exitValue();
      if (bHasError) {
        throw new Exception("execute error:" + result);
      }
    } catch (Exception e) {
      throw e;
    }
    return result;
  }
예제 #27
0
 private String getSDKProperties(String javaPath, String path) throws IOException {
   Runtime runtime = Runtime.getRuntime();
   try {
     String[] command = new String[5];
     command[0] = javaPath;
     command[1] = "-classpath"; // NOI18N
     command[2] =
         InstalledFileLocator.getDefault()
             .locate(
                 "modules/ext/org-netbeans-modules-visage-platform-probe.jar",
                 "org.netbeans.modules.visage.platform",
                 false)
             .getAbsolutePath(); // NOI18N
     command[3] = "org.netbeans.modules.visage.platform.wizard.SDKProbe"; // NOI18N
     command[4] = path;
     final Process process = runtime.exec(command);
     // PENDING -- this may be better done by using ExecEngine, since
     // it produces a cancellable task.
     process.waitFor();
     int exitValue = process.exitValue();
     if (exitValue != 0) throw new IOException();
     return command[2];
   } catch (InterruptedException ex) {
     IOException e = new IOException();
     ErrorManager.getDefault().annotate(e, ex);
     throw e;
   }
 }
예제 #28
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;
    }
  }
예제 #29
0
 @Override
 protected void waitForExit() throws ErlRuntimeException {
   if (process != null) {
     int i = 500;
     // may have to wait for crash dump to be written
     while (i-- > 0 && exitCode < 0) {
       exitCode = -1;
       try {
         Thread.sleep(POLL_INTERVAL * 2);
         exitCode = process.exitValue();
       } catch (final IllegalThreadStateException e) {
       } catch (final InterruptedException e) {
       }
       if (exitCode > 0) {
         throw new ErlRuntimeException(
             String.format("Runtime %s died with exit code %d", getNodeName(), exitCode));
       }
     }
     if (exitCode < 0) {
       ErlLogger.warn("Runtime %s died, but process is still running; killing it", getNodeName());
       throw new ErlRuntimeException(
           String.format("Runtime %s died with exit code unknown", getNodeName()));
     }
   }
 }
  public ProcessInfo setUpCoordinator(
      String file,
      String mainProcess,
      String delegatedProcesses,
      ConsoleWatcher... additionalWatches)
      throws Exception {
    Process process =
        startSecondJVM(
            CMLJ.class,
            new String[] {
              "-process",
              mainProcess,
              "-delegatedprocessed",
              delegatedProcesses,
              "-mode",
              "server",
              "-cosimport",
              port.toString(),
              "-simulate",
              file.replace('/', File.separatorChar)
            });
    ConsoleWatcher watch = new ConsoleWatcher("coordinator", ConsoleWatcher.FINISHED_MATCH_TEXT);
    ConsoleWatcher listningWatch = new ConsoleWatcher("coordinator", "Waiting for clients...");
    this.watched.add(watch);

    ConsoleWatcher[] watches = new ConsoleWatcher[2 + additionalWatches.length];
    watches[0] = watch;
    watches[1] = listningWatch;
    if (additionalWatches.length > 0) {
      int i = 2;
      for (int j = 0; j < additionalWatches.length; j++, i++) {
        watches[i] = additionalWatches[j];
      }
    }
    startAutoRead(process, "server", quiet, watches);

    int time = 0;
    final int RETRY_WAIT = 200;
    while (!listningWatch.isMatched()) {
      int exit = 0;
      try {
        try {
          // the build server is slow
          Thread.sleep(500);
        } catch (InterruptedException e) {

        }
        process.exitValue();
        exit = -1;
      } catch (IllegalThreadStateException e) {

      }
      if (time * 1000 >= DEFAULT_TIMEOUT || exit == -1) {
        throw new TimeoutException("Server never started to listen for clients");
      }
      Utils.milliPause(RETRY_WAIT);
      time += RETRY_WAIT;
    }
    return new ProcessInfo(process, watch);
  }