private static void testDynamicNumberOfGCThreads(String gcFlag) throws Exception {
    // UseDynamicNumberOfGCThreads and TraceDynamicGCThreads enabled
    String[] baseArgs = {
      "-XX:+" + gcFlag,
      "-Xmx10M",
      "-XX:+UseDynamicNumberOfGCThreads",
      "-Xlog:gc+task=trace",
      GCTest.class.getName()
    };

    // Base test with gc and +UseDynamicNumberOfGCThreads:
    ProcessBuilder pb_enabled = ProcessTools.createJavaProcessBuilder(baseArgs);
    verifyDynamicNumberOfGCThreads(new OutputAnalyzer(pb_enabled.start()));

    // Ensure it also works on uniprocessors or if user specifies -XX:ParallelGCThreads=1:
    String[] extraArgs = {
      "-XX:+UnlockDiagnosticVMOptions",
      "-XX:+ForceDynamicNumberOfGCThreads",
      "-XX:ParallelGCThreads=1"
    };
    String[] finalArgs = new String[baseArgs.length + extraArgs.length];
    System.arraycopy(extraArgs, 0, finalArgs, 0, extraArgs.length);
    System.arraycopy(baseArgs, 0, finalArgs, extraArgs.length, baseArgs.length);
    pb_enabled = ProcessTools.createJavaProcessBuilder(finalArgs);
    verifyDynamicNumberOfGCThreads(new OutputAnalyzer(pb_enabled.start()));

    // Turn on parallel reference processing
    String[] parRefProcArg = {"-XX:+ParallelRefProcEnabled", "-XX:-ShowMessageBoxOnError"};
    String[] parRefArgs = new String[baseArgs.length + parRefProcArg.length];
    System.arraycopy(parRefProcArg, 0, parRefArgs, 0, parRefProcArg.length);
    System.arraycopy(baseArgs, 0, parRefArgs, parRefProcArg.length, baseArgs.length);
    pb_enabled = ProcessTools.createJavaProcessBuilder(parRefArgs);
    verifyDynamicNumberOfGCThreads(new OutputAnalyzer(pb_enabled.start()));
  }
 @Override
 public void execute() throws LifecycleException {
   Process process = null;
   try {
     List<String> command = new ShutdownAdminServerCommand().getCommand();
     ProcessBuilder builder = new ProcessBuilder(command);
     builder.redirectErrorStream(true);
     process = builder.start();
     Thread consoleConsumer =
         new Thread(new ConsoleConsumer(process, configuration.isOutputToConsole()));
     consoleConsumer.setDaemon(true);
     consoleConsumer.start();
     while (isServerRunning()) {
       try {
         Thread.sleep(500L);
       } catch (InterruptedException e) {
         logger.log(Level.INFO, "Container shutdown interrupted");
         throw e;
       }
     }
     logger.log(Level.INFO, "Stopped WebLogic Server.");
     return;
   } catch (Exception ex) {
     throw new LifecycleException("Container shutdown failed.", ex);
   }
 }
  public static void main(String args[]) throws Exception {
    OutputAnalyzer output;
    WhiteBox wb = WhiteBox.getWhiteBox();

    // Grab my own PID
    String pid = Integer.toString(ProcessTools.getProcessId());
    ProcessBuilder pb = new ProcessBuilder();

    // Use WB API to alloc and free with the mtTest type
    long memAlloc3 = wb.NMTMalloc(128 * 1024);
    long memAlloc2 = wb.NMTMalloc(256 * 1024);
    wb.NMTFree(memAlloc3);
    long memAlloc1 = wb.NMTMalloc(512 * 1024);
    wb.NMTFree(memAlloc2);

    // Use WB API to ensure that all data has been merged before we continue
    if (!wb.NMTWaitForDataMerge()) {
      throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
    }

    // Run 'jcmd <pid> VM.native_memory summary'
    pb.command(new String[] {JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "summary"});
    output = new OutputAnalyzer(pb.start());
    output.shouldContain("Test (reserved=512KB, committed=512KB)");

    // Free the memory allocated by NMTAllocTest
    wb.NMTFree(memAlloc1);

    // Use WB API to ensure that all data has been merged before we continue
    if (!wb.NMTWaitForDataMerge()) {
      throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
    }
    output = new OutputAnalyzer(pb.start());
    output.shouldNotContain("Test (reserved=");
  }
Ejemplo n.º 4
0
  private void kill_pcscd() {
    File f = new File(ctx.getFilesDir() + "/pcscd/pcscd.pid");
    FileInputStream fis = null;
    if (f.exists()) {
      try {
        // read pid
        fis = new FileInputStream(f);
        byte[] pid = new byte[fis.available()];
        int num = fis.read(pid);

        if (num > 0) {
          // kill pcsc daemon
          ProcessBuilder pb = new ProcessBuilder("kill", "-9", new String(pid, "UTF-8"));
          pb.start();
        }

        // cleanup files
        String del = ctx.getFilesDir() + "/pcscd/*";
        ProcessBuilder pb = new ProcessBuilder("rm", "-r", del);
        pb.start();
      } catch (IOException e) {
        logger.error("Killing the pcsc daemon or cleanup failed.", e);
      } finally {
        try {
          if (fis != null) {
            fis.close();
          }
        } catch (IOException e) {
          // ignore
        }
      }
    }
  }
Ejemplo n.º 5
0
  public static String extractClassPathUsingMvnV2(String projectRoot, boolean installIt)
      throws IOException, InterruptedException {
    if (installIt) {
      // Prior installation to produce full pom (in case of multi modules)
      System.out.println("[MAVEN] Installing module....");
      ProcessBuilder proc0 = new ProcessBuilder("mvn", "install");
      proc0.directory(new File(projectRoot));
      proc0.start().waitFor();
    }

    System.out.println("[MAVEN] Dependencies extraction...");

    // Extract dependencies
    ProcessBuilder proc1 = new ProcessBuilder("mvn", "dependency:build-classpath");
    proc1.directory(new File(projectRoot));
    Process start = proc1.start();

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

    String s = null;
    String cp = "";

    while ((s = stdInput.readLine()) != null) {
      if (!s.startsWith("[")
          && !s.contains(" ")
          && !s.contains("http://")
          && !s.contains("https://")) {
        cp += (cp.length() == 0 ? "" : ":") + s;
      }
    }

    return cp;
  }
Ejemplo n.º 6
0
  /**
   * Tries to get the java executable command with which the current JVM was started. Returns null,
   * if the command could not be found.
   *
   * @return The java executable command.
   */
  public static String getJavaCommandPath() {
    File javaHome = new File(System.getProperty("java.home"));

    String path1 = new File(javaHome, "java").getAbsolutePath();
    String path2 = new File(new File(javaHome, "bin"), "java").getAbsolutePath();

    try {
      ProcessBuilder bld = new ProcessBuilder(path1, "-version");
      Process process = bld.start();
      if (process.waitFor() == 0) {
        return path1;
      }
    } catch (Throwable t) {
      // ignore and try the second path
    }

    try {
      ProcessBuilder bld = new ProcessBuilder(path2, "-version");
      Process process = bld.start();
      if (process.waitFor() == 0) {
        return path2;
      }
    } catch (Throwable tt) {
      // no luck
    }
    return null;
  }
Ejemplo n.º 7
0
  private static void testGCId(String gcFlag, String logFlag) throws Exception {
    // GCID logging enabled
    ProcessBuilder pb_enabled =
        ProcessTools.createJavaProcessBuilder(
            "-XX:+" + gcFlag,
            "-XX:+" + logFlag,
            "-Xmx10M",
            "-XX:+PrintGCID",
            GCTest.class.getName());
    verifyContainsGCIDs(new OutputAnalyzer(pb_enabled.start()));

    // GCID logging disabled
    ProcessBuilder pb_disabled =
        ProcessTools.createJavaProcessBuilder(
            "-XX:+" + gcFlag,
            "-XX:+" + logFlag,
            "-Xmx10M",
            "-XX:-PrintGCID",
            GCTest.class.getName());
    verifyContainsNoGCIDs(new OutputAnalyzer(pb_disabled.start()));

    // GCID logging default
    ProcessBuilder pb_default =
        ProcessTools.createJavaProcessBuilder(
            "-XX:+" + gcFlag, "-XX:+" + logFlag, "-Xmx10M", GCTest.class.getName());
    verifyContainsNoGCIDs(new OutputAnalyzer(pb_default.start()));
  }
Ejemplo n.º 8
0
 private void installOnMac(File location)
     throws IOException, ZipException, InterruptedException {
   File installDir = new File(location + "/adb_tools.zip");
   if (!installDir.exists()) {
     installDir.getParentFile().mkdirs();
     InputStream input =
         this.getClass().getResourceAsStream("/JDroidLib/res/adb_tools/adb-mac.zip");
     File adb_tools = new File(location + "/adb_tools.zip");
     OutputStream output = new FileOutputStream(adb_tools);
     int readBytes = 0;
     byte[] buffer = new byte[4096];
     while ((readBytes = input.read(buffer)) > 0) {
       output.write(buffer, 0, readBytes);
     }
     input.close();
     output.close();
     ZipFile zip = new ZipFile(adb_tools);
     zip.extractAll(location.toString());
     ProcessBuilder process = new ProcessBuilder("chmod", "a+x", location + "/adb");
     Process pr = process.start();
     Thread.sleep(200);
     pr.destroy();
     process = new ProcessBuilder("chmod", "a+x", location + "/fastboot");
     pr = process.start();
     Thread.sleep(200);
     pr.destroy();
     adb_tools.delete();
   }
 }
Ejemplo n.º 9
0
  public static void restartApplication() throws URISyntaxException, IOException {
    final String javaBin =
        System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
    final File currentJar =
        new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI());
    System.out.println(currentJar.getAbsolutePath());
    /* is it a jar file? */
    if (currentJar.getName().endsWith("exe")) {

      final ArrayList<String> command = new ArrayList<String>();
      // command.add(javaBin);
      // command.add("-jar");
      command.add(currentJar.getPath());

      final ProcessBuilder builder = new ProcessBuilder(command);
      builder.start();
      System.exit(0);
    }

    if (!currentJar.getName().endsWith(".jar")) return;

    /* Build command: java -jar application.jar */
    final ArrayList<String> command = new ArrayList<String>();
    command.add(javaBin);
    command.add("-jar");
    command.add(currentJar.getPath());

    final ProcessBuilder builder = new ProcessBuilder(command);
    builder.start();
    System.exit(0);
  }
Ejemplo n.º 10
0
  /*
   * Combines audio input with video input at specified time
   * @see javax.swing.SwingWorker#doInBackground()
   */
  @Override
  protected Void doInBackground() throws Exception {

    // Extract the audio from the video and save it as a hidden file in MP3Files
    String cmd = "ffmpeg -y -i " + videoPath + " -map 0:1 ./MP3Files/.vidAudio.mp3";

    ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", cmd);
    Process process = builder.start();
    process.waitFor();

    for (int i = 1; i < 25; i++) { // Update progress bar when above process is complete
      Thread.sleep(40);
      progress.updateProgress(i);
    }
    if (time == 0) {
      // Create a hidden mp3 file output.mp3 that combines the video audio and selected mp3 audio at
      // time 0
      cmd =
          "ffmpeg -y -i "
              + audioPath
              + " -i ./MP3Files/.vidAudio.mp3 -filter_complex amix=inputs=2 ./MP3Files/.output.mp3";
    } else {
      // Create a hidden mp3 file output.mp3 that combines the video audio and selected mp3 audio at
      // specified time
      cmd =
          "ffmpeg -y -i "
              + audioPath
              + " -i ./MP3Files/.vidAudio.mp3 -filter_complex \"[0:0]adelay="
              + time
              + "[aud1];[aud1][1:0]amix=inputs=2\" ./MP3Files/.output.mp3";
    }

    builder = new ProcessBuilder("/bin/bash", "-c", cmd);
    process = builder.start();
    process.waitFor();

    for (int i = 1; i < 50; i++) { // Update progress bar
      Thread.sleep(40);
      progress.updateProgress(25 + i);
    }

    // Creates an output.avi file from merging existing video stream (1:0) and combined audio (0:0)
    cmd =
        "ffmpeg -i "
            + videoPath
            + " -i ./MP3Files/.output.mp3 -map 0:0 -map 1:0 -acodec copy -vcodec copy ./VideoFiles/"
            + name
            + ".avi";

    builder = new ProcessBuilder("/bin/bash", "-c", cmd);
    process = builder.start();
    process.waitFor();

    for (int i = 1; i < 25; i++) { // Update progress bar
      Thread.sleep(40);
      progress.updateProgress(75 + i);
    }

    return null;
  }
Ejemplo n.º 11
0
  protected void prepare() throws Exception {
    ProcessBuilder pb = createJarProcessBuilder("cf", "foo.jar", "Foo.class", "Bar.class");
    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    dump(output, "ctw-foo.jar");
    output.shouldHaveExitValue(0);

    pb = createJarProcessBuilder("cf", "bar.jar", "Foo.class", "Bar.class");
    output = new OutputAnalyzer(pb.start());
    dump(output, "ctw-bar.jar");
    output.shouldHaveExitValue(0);
  }
  public static void main(String[] args) throws Exception {
    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+PrintWarnings=8", "-version");

    OutputAnalyzer output = new OutputAnalyzer(pb.start());
    output.shouldContain("Improperly specified VM option 'PrintWarnings=8'");
    output.shouldHaveExitValue(1);

    pb = ProcessTools.createJavaProcessBuilder("-XX:-PrintWarnings=8", "-version");

    output = new OutputAnalyzer(pb.start());
    output.shouldContain("Improperly specified VM option 'PrintWarnings=8'");
    output.shouldHaveExitValue(1);
  }
Ejemplo n.º 13
0
  /**
   * This method runs the ProcessBuilder and waits for it to finish. At the end it checks the return
   * state from the process and if it is a failure it prints the last line of the console output.
   *
   * @param builder
   */
  private void bashProcess(ProcessBuilder builder) {
    Process process = null;
    builder.redirectErrorStream(true);
    try {
      process = builder.start();

    } catch (IOException e1) {
      e1.printStackTrace();
    }
    InputStream stdout = process.getInputStream();
    BufferedReader stdoutBuffered = new BufferedReader(new InputStreamReader(stdout));
    String line = null;
    String last = null;
    try {
      while ((line = stdoutBuffered.readLine()) != null) {
        last = line;
        if (isCancelled()) {
          process.destroy();
          return;
        }
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    }
    try {
      if (process.waitFor() != 0) {
        firePropertyChange("failure", null, last);
        errorState = true;
      }
    } catch (InterruptedException e1) {
      e1.printStackTrace();
    }
  }
Ejemplo n.º 14
0
 public void setUpSolrFile(String url) throws Exception {
   if (setUpIsDone) {
     return;
   }
   // do the setup
   File testDir = (Paths.get(getClass().getResource("/" + testFile).toURI()).getParent()).toFile();
   ProcessBuilder pb =
       new ProcessBuilder("java", "-Durl=" + url + "/update", "-jar", "post.jar", testFile);
   pb.directory(testDir);
   LOGGER.log(Level.FINE, "Starting SOLR import");
   final Process command = pb.start();
   LOGGER.log(Level.FINE, "Started SOLR import");
   String line;
   BufferedReader bri = new BufferedReader(new InputStreamReader(command.getInputStream()));
   BufferedReader bre = new BufferedReader(new InputStreamReader(command.getErrorStream()));
   while ((line = bri.readLine()) != null) {
     LOGGER.log(Level.FINE, line);
   }
   bri.close();
   while ((line = bre.readLine()) != null) {
     LOGGER.log(Level.FINE, line);
   }
   bre.close();
   int i = command.waitFor();
   assertTrue(i == 0);
   LOGGER.log(Level.FINE, "SOLR import DONE!");
   setUpIsDone = true;
 }
  /**
   * Génère une représentation graphique du processeur et de ses flux dans un fichier image.
   *
   * <p>Le logiciel externe dot de graphviz est utilisé pour construire la représentation.
   *
   * @return le nom du fichier image contenant la représentation.
   * @throws IOException Signals that an I/O exception has occurred.
   */
  public String generateGraph() throws IOException {
    final String fileName = "graph-" + this;
    final PrintStream out = new PrintStream(fileName);

    out.println("digraph {");
    out.println("\trankdir=LR;");
    out.println("\tpenwidth=1;");
    out.println("\tpencolor=black;");
    out.println("\tbgcolor=white;");
    out.println("\tmargin=0;");
    out.println("\tcompound=true;pack=true;");
    generateGraphRepresentation(out);
    out.println("}");

    String windowsHack;
    if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1) {
      windowsHack = "..\\graphviz-bin\\release\\bin\\";
    } else windowsHack = "";

    final ProcessBuilder pb =
        new ProcessBuilder(windowsHack + "dot", "-Tpng", "-o" + fileName + ".png", fileName);
    final Process process = pb.start();
    try {
      process.waitFor();
    } catch (final InterruptedException e) {
      e.printStackTrace();
    }

    final java.io.File f = new java.io.File(fileName);
    f.delete();
    return fileName + ".png";
  }
Ejemplo n.º 16
0
 private Process startProcess() throws ExecFailedException {
   try {
     return processBuilder.start();
   } catch (IOException ioe) {
     throw new ExecFailedException(this, ioe);
   }
 }
  @Before
  public void setUp() throws Exception {

    FileUtils.deleteDirectory(SVN_DIR);

    System.out.println("setup...");
    SVN_DIR.mkdirs();

    ProcessBuilder builder = new ProcessBuilder(SVNADMIN_EXEC, "create", SVN_DIR.getAbsolutePath());
    builder.redirectErrorStream(true);
    Process process = builder.start();
    process.waitFor();

    FileUtils.writeStringToFile(
        new File(SVN_DIR, "conf/svnserve.conf"), "[general]\npassword-db = passwd", null);
    FileUtils.writeStringToFile(new File(SVN_DIR, "conf/passwd"), "[users]\nguest = guest", null);
    System.out.println("setup ok.");

    writer = context.mock(LrdWriter.class);

    repositoryBean = new RepositoryBean();
    repositoryBean.setUrl(SVN_URL);
    repositoryBean.setUserName(SVN_USER);
    repositoryBean.setPassword(SVN_PASS);
  }
Ejemplo n.º 18
0
  public static void mountExt4() {
    makeDirectory(Constants.MOUNT_PATH);

    try {
      final ProcessBuilder pb =
          new ProcessBuilder("mount", Constants.NBD_DEVICE, Constants.MOUNT_PATH);
      final StringBuilder err = new StringBuilder();

      final Process startClientProcess = pb.start();
      final BufferedReader stdErr =
          new BufferedReader(
              new InputStreamReader(startClientProcess.getErrorStream(), StandardCharsets.UTF_8));
      final BufferedReader stdOut =
          new BufferedReader(
              new InputStreamReader(startClientProcess.getInputStream(), StandardCharsets.UTF_8));

      startClientProcess.waitFor();
      errorHandler(startClientProcess, stdErr, stdOut, err);

    } catch (final IOException e) {
      throw new RuntimeException(e);
    } catch (final InterruptedException e) {
      throw new RuntimeException(e);
    }
  }
  public Process createProcess() throws ExecutionException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("Executing [" + getCommandLineString() + "]");
    }

    List<String> commands;
    try {
      checkWorkingDirectory();

      if (StringUtil.isEmptyOrSpaces(myExePath)) {
        throw new ExecutionException(
            IdeBundle.message("run.configuration.error.executable.not.specified"));
      }

      commands = CommandLineUtil.toCommandLine(myExePath, myProgramParams.getList());
    } catch (ExecutionException e) {
      LOG.warn(e);
      throw e;
    }

    try {
      ProcessBuilder builder = new ProcessBuilder(commands);
      setupEnvironment(builder.environment());
      builder.directory(myWorkDirectory);
      builder.redirectErrorStream(myRedirectErrorStream);
      return builder.start();
    } catch (IOException e) {
      LOG.warn(e);
      throw new ProcessNotCreatedException(e.getMessage(), e, this);
    }
  }
Ejemplo n.º 20
0
 @Override
 public void run() {
   try {
     // File meteocalc = new
     // File(facade.getConstants().getMeteoOrderDir()+facade.getConstants().getMeteoOrderCommand());
     String[] command = {
       "CMD", "/C", facade.getConstants().getImageOrderCommand(), getId().toString()
     };
     ProcessBuilder processBuilder = new ProcessBuilder(command);
     processBuilder.directory(new File(facade.getConstants().getImageOrderDir()));
     LOG.debug("ImageOrder #" + this.getId() + " prepared for execution. Starting.");
     Process process = processBuilder.start();
     process.waitFor();
     LOG.debug("ImageOrder #" + this.getId() + " finished execution");
     facade.getOrderProcessor().releaseProcessor(this);
     String url =
         facade.getConstants().getMeteoOrderDir()
             + "OUT_IMAGES/"
             + getId()
             + "."
             + facade.getConstants().getImageFormat();
     if (new File(url).canRead()) {
       setImageURL(url);
       setStatus(Status.READY_FOR_PICKUP);
     } else {
       throw new Exception("Image file was not created or cannot to be read");
     }
   } catch (Exception e) {
     LOG.error(e);
     throw new RuntimeException(e);
   }
 }
 @Override
 public CommandRunner.CommandOutput runCommandAndWaitForExit(
     File workingDir, List<String> arguments) throws IOException, InterruptedException {
   File binary = new File(arguments.get(0));
   if (!binary.exists()) {
     logger.error("Binary {} does not exists, fix your configuration!", binary.getAbsolutePath());
     return createErrorCommandOutput();
   }
   if (!binary.canExecute()) {
     logger.error(
         "Binary {} can't be executed, fix your configuration!", binary.getAbsolutePath());
     return createErrorCommandOutput();
   }
   ProcessBuilder pb = new ProcessBuilder(arguments);
   pb.directory(workingDir);
   Process process = pb.start();
   ByteArrayOutputStream stderr = new ByteArrayOutputStream();
   ByteArrayOutputStream stdout = new ByteArrayOutputStream();
   CommandRunnerImpl.StreamGobbler sgerr =
       new CommandRunnerImpl.StreamGobbler(process.getErrorStream(), stderr);
   CommandRunnerImpl.StreamGobbler sgout =
       new CommandRunnerImpl.StreamGobbler(process.getInputStream(), stdout);
   sgerr.start();
   sgout.start();
   int exitCode = process.waitFor();
   sgerr.join();
   sgout.join();
   CommandRunner.CommandOutput result =
       new CommandRunner.CommandOutput(stdout.toByteArray(), stderr.toByteArray());
   result.setExitCode(exitCode);
   return result;
 }
  private static void checkIsAvailableAndGetVersion() {
    ProcessBuilder pb = new ProcessBuilder(COMMAND, "--version");
    pb.redirectErrorStream(true);
    Process p = null;
    try {
      p = pb.start();
      p.waitFor();

      perconaToolkitVersion = StreamUtil.getStreamContents(p.getInputStream());
      if (perconaToolkitVersion != null) {
        perconaToolkitVersion = perconaToolkitVersion.replaceAll("\n|\r", "");
      }
      available = true;
      log.info("Using percona toolkit: " + perconaToolkitVersion);
    } catch (IOException e) {
      available = false;
    } catch (InterruptedException e) {
      available = false;
    } finally {
      if (p != null) {
        StreamUtil.closeQuietly(p.getErrorStream());
        StreamUtil.closeQuietly(p.getInputStream());
        StreamUtil.closeQuietly(p.getOutputStream());
        p.destroy();
      }
    }
  }
Ejemplo n.º 23
0
  public void createMatchTable() throws IOException, InterruptedException {
    addReport("Matching keypoints started");

    //		File matchTable = new File(FileHelper.mergePath(imageDirectory,
    // keypointMatchTableFilename));
    //
    //		if(matchTable.exists()) {
    //			addReport("Match table \""+keypointMatchTableFilename+"\" exists, therefore skip
    // matching");
    //			return;
    //		}

    ProcessBuilder pb =
        new ProcessBuilder(
            keypointMatcherPath,
            FileHelper.mergePath(imageDirectory, imageListKeysFilename),
            FileHelper.mergePath(imageDirectory, keypointMatchTableFilename));
    pb.directory(new File(imageDirectory));
    Process p = pb.start();

    addReport(p.getInputStream(), p.getErrorStream());

    if (p.waitFor() != 0) {
      addReport("Matching keypoints error");
      stop();
    }
  }
  public static void main (String[] args) {

    System.out.println(\u00CB);

    try {
        if (!Platform.shouldSAAttach()) {
            System.out.println("SA attach not expected to work - test skipped.");
            return;
        }
        int pid = ProcessTools.getProcessId();
        JDKToolLauncher jmap = JDKToolLauncher.create("jmap")
                                              .addToolArg("-F")
                                              .addToolArg("-dump:live,format=b,file=" + dumpFile)
                                              .addToolArg(Integer.toString(pid));
        ProcessBuilder pb = new ProcessBuilder(jmap.getCommand());
        OutputBuffer output = ProcessTools.getOutput(pb);
        Process p = pb.start();
        int e = p.waitFor();
        System.out.println("stdout:");
        System.out.println(output.getStdout());
        System.out.println("stderr:");
        System.out.println(output.getStderr());

        if (e != 0) {
            throw new RuntimeException("jmap returns: " + e);
        }
        if (! new File(dumpFile).exists()) {
            throw new RuntimeException("dump file NOT created: '" + dumpFile + "'");
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException("Test failed with: " + t);
    }
  }
Ejemplo n.º 25
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);
    }
  }
Ejemplo n.º 26
0
  private static String readProcessOutput(String command, String arguments) {
    String result = "";
    ProcessBuilder pb = new ProcessBuilder(command, arguments);
    pb.redirectErrorStream(true);
    try {
      Process process = pb.start();
      InputStream stdout = process.getInputStream();
      final BufferedReader brstdout = new BufferedReader(new InputStreamReader(stdout));
      String line = null;

      try {
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = brstdout.readLine()) != null) {
          stringBuilder.append(line);
        }

        result = stringBuilder.toString();
      } catch (Exception e) {
      } finally {
        IOUtils.closeQuietly(brstdout);
        IOUtils.closeQuietly(stdout);
      }

    } catch (Throwable e) {
      e.printStackTrace();
    }
    return result;
  }
Ejemplo n.º 27
0
 /** 读取当前网速 */
 public static long getNetSpeed() {
   ProcessBuilder cmd;
   long readBytes = 0;
   BufferedReader rd = null;
   try {
     String[] args = {"/system/bin/cat", "/proc/net/dev"};
     cmd = new ProcessBuilder(args);
     Process process = cmd.start();
     rd = new BufferedReader(new InputStreamReader(process.getInputStream()));
     String line;
     // int linecount = 0;
     while ((line = rd.readLine()) != null) {
       // linecount++;
       if (line.contains("lan0") || line.contains("eth0")) {
         String[] delim = line.split(":");
         if (delim.length >= 2) {
           readBytes = parserNumber(delim[1].trim());
           break;
         }
       }
     }
     rd.close();
   } catch (Exception ex) {
     ex.printStackTrace();
   } finally {
     if (rd != null) {
       try {
         rd.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
   }
   return readBytes;
 }
Ejemplo n.º 28
0
  public static void main(String[] args) throws Exception {
    final float heapSizeMegs = Runtime.getRuntime().maxMemory() / 1024L / 1024L;
    if (heapSizeMegs > 511.0F) {
      LauncherFrame.main(args);
    } else {
      try {
        final String pathToJar =
            MCLauncher.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();

        final ArrayList<String> params = new ArrayList<String>();

        params.add("javaw");
        params.add("-Xmx1024m");
        params.add("-Dsun.java2d.noddraw=true");
        params.add("-Dsun.java2d.d3d=false");
        params.add("-Dsun.java2d.opengl=false");
        params.add("-Dsun.java2d.pmoffscreen=false");

        params.add("-classpath");
        params.add(pathToJar);
        params.add("com.kokakiwi.mclauncher.LauncherFrame");
        final ProcessBuilder pb = new ProcessBuilder(params);
        final Process process = pb.start();
        if (process == null) {
          throw new Exception("!");
        }
        System.exit(0);
      } catch (final Exception e) {
        e.printStackTrace();
        LauncherFrame.main(args);
      }
    }
  }
Ejemplo n.º 29
0
  protected void runPub(
      IContainer container, final MessageConsole console, List<String> args, boolean wait) {

    stringBuilder = new StringBuilder();
    ProcessBuilder builder = new ProcessBuilder();
    builder.directory(container.getLocation().toFile());
    builder.redirectErrorStream(true);
    builder.command(args);

    final Process process;
    try {
      process = builder.start();
      final Thread stdoutThread =
          new Thread(
              new Runnable() {
                @Override
                public void run() {
                  try {
                    copy(process.getInputStream(), console);
                  } catch (IOException e) {
                    // do nothing
                  }
                }
              });
      stdoutThread.start();
      if (wait) {
        process.waitFor();
      }
    } catch (IOException e) {
      String message = NLS.bind(PubMessages.RunPubJob_failed, command, e.toString());
      console.println(message);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
Ejemplo n.º 30
0
    @Override
    public Process execute(List<String> command, boolean terminal) throws Exception {
      if (terminal) {
        File commandFile = File.createTempFile("cmd-", "");
        commandFile.deleteOnExit();

        String commandPath = commandFile.toString();
        String commandLine = getCommandLine(command);
        IOUtil.writeUTF8(commandFile, commandLine);

        List<String> chmodCommand = new ArrayList<String>();
        chmodCommand.add("chmod");
        chmodCommand.add("a+x");
        chmodCommand.add(commandPath);

        ProcessBuilder chmodProcessBuilder = new ProcessBuilder(chmodCommand);
        Process chmodProcess = chmodProcessBuilder.start();
        chmodProcess.waitFor();

        List<String> terminalCommand = new ArrayList<String>();
        terminalCommand.add("open");
        terminalCommand.add("-b");
        terminalCommand.add("com.apple.terminal");
        terminalCommand.add(commandPath);
        command = terminalCommand;
      }

      return super.execute(command, terminal);
    }